阅读 289

nginx解决跨域问题的实例方法

在本篇文章里小编给各位分享了关于nginx怎么解决跨域问题的方法和实例代码,需要的朋友们参考下。

前后端分离,使用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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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).
# 代理服务端接口

1
2
3
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)

1
2
3
4
5
6
7
axios.post('/api/index2')
.then( (response) =>{
console.log(response);
})
.catch( (error)=> {
console.log(error);
});


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



文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐