信息发布→ 登录 注册 退出

nginx跨域问题如何解决

发布时间:2023-05-13

点击量:

前后端分离,使用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  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

内容扩展思考:

1).
# 代理服务端接口

location /api/ {
proxy_pass http://localhost:8080/;# 代理接口地址
}

代理接口地址只到8080,那么他会自动将后台项目的名称加上??? 比如接口是http://148.70.110.87:8080/项目名称/方法名称 。。。

2).js 中是这样请求的 ,nginx是按照您上面的配置,但是请求出错http://148.70.110.87/api/index2 404 (not found)

axios.post('/api/index2')
.then( (response) =>{
console.log(response);
})
.catch( (error)=> {
console.log(error);
});

3).第三个步骤,测试,实在看不懂要是能有相关的代码就好了

标签:# 是这样  # 代理服务器  # 看不懂  # 第三个  # 为例  # 重写  # 能有  # 他会  # 将其  # nginx  # 服务端  # http  # JS  # 接口  # Static  # webpack  # html  # vue.js  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!