nginx怎么解决跨域


本文摘自PHP中文网,作者(*-*)浩,侵删。

前后端分离,使用nginx解决跨域问题

前端:vue.js+nodejs+webpack

后台:SpringBoot

反向代理服务器:nginx

思想:将前端代码打包,让nginx指向静态资源,nginx对后台请求进行转发。

1、将前端代码打包:

1

npm run build

会生成一个dist文件夹。包含一个index.html文件和一个static文件夹,路径以我本地为例:

/Users/xxx/ideaProjects/webtest/dist

2、打开

/usr/local/etc/nginx目录下的nginx.conf,在server中添加如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

listen       80; #原为8080,避免冲突,更改为80

        server_name  localhost;

 

        #charset koi8-r;

 

        #access_log  logs/host.access.log  main;

 

 

        location / {

            root   /Users/xxx/ideaProjects/webtest/dist;

            index  index.html;

             

            # 此处用于处理 Vue、Angular、React 使用H5 的 History时 重写的问题

            if (!-e $request_filename) {

                rewrite ^(.*) /index.html last;

                break;

            }

        }

 

 

        # 代理服务端接口

        location /api/ {

            proxy_pass http://localhost:8080/;# 代理接口地址

        }

测试

前端发送请求:http://localhost/test ,vue-router将其重定向为http://localhost/api/demo/1,实际访问是http://localhost:8080/demo/1。

直接向后台发送请求:访问http://localhost/api/demo/1,实际访问是:http://localhost:8080/demo/1

更多Nginx相关技术文章,请访问Nginx使用教程栏目进行学习!

以上就是nginx怎么解决跨域的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

nginx主要特点介绍

nginx怎么发音

nginx和haproxy的区别

nginx为什么会出现404

用了dubbo还有必要用nginx

nginx负载均衡策略有哪些

nginx伪静态规则配置

关于linux下如何查看nginx的并发连接数和连接状态的详细介绍

使用 nginx 反向代理多个 docker 容器

先安装nginx再加健康模块么

更多相关阅读请进入《nginx》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...