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

时间:2023-03-09 13:16:55
前后端分离,使用nginx解决跨域问题

前端:vue.js+nodejs+webpack

后台:SpringBoot

反向代理服务器:nginx

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

1、将前端代码打包:

npm run build

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

/Users/xxx/ideaProjects/webtest/dist

2、打开

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

        listen       ; #原为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/;# 代理接口地址
}

3、测试

前端发送请求: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