这篇文章将为大家详细讲解有关使用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);
});
关于使用nginx怎么解决跨域问题就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。