位置:- 正文

Vue2解决跨域的3种方式(vue2.0解决跨域问题)

编辑:rootadmin
Vue2解决跨域的3种方式 1. 跨域的三种方式1.1 jsonp

以前的技术,通过<script>标签跨域请求,服务器端返回的是符合js语法的函数调用,函数的形参即数据

1.2 CORS

跨域资源共享,需要服务器端进行配置

//express中配置corsconst cors = require("cors")app.use(cors())1.3  服务器代理

(1) 通过在vue.config.js中配置proxy实现跨域 (开发阶段)

(2) 通过Nginx服务器代理实现跨域 (生产阶段)

## 2. Nginx服务器代理

Nginx (engine x) 是一个高性能的HTTP和反向代理web服务器 可以实现vue项目中的跨域请求

我们真实的服务器不应该直接暴露到公网上去,否则更加容易泄露服务器的信息,也更加容易受到攻击。一个比较“平民化”的方案是使用Nginx反向代理它。

一台具有公网的Nginx服务器可以代理和它能进行内网通信的真实的服务器。让我们的服务器不直接对外暴露,增加其抗风险能力。

2.1 下载

http://nginx.org/en/download.html|  nginx/Windows-1.10.3 |

2.2 nginx在windows系统中如何启动、重启、停止

在nginx文件夹中打开cmd

(如果是powershell不能直接使用cmd命令:  输入cmd回车即可)

//基本命令操作:nginx -v //查看nginx的版本号start nginx //启动nginxnginx -s stop //快速停止或关闭nginxnginx -s quit //正常停止或关闭nginxnginx -s reload //配置文件nginx.conf修改重装载命令2.3 启动nginx

start nginx 在地址栏输入: localhost:80即可打开默认首页

2.4 修改前端vue项目中的url

在config.js中修改baseURL

//原设置baseURL: 'http://localhost:3000'//修改为baseURL: '/api'2.5 打包vue项目

npm run build 把dist文件夹放在nginx根目录

2.6 修改nginx的 conf/nginx.confserver { listen 80; #nginx服务器端口 server_name localhost; #nginx域名 location / { root dist; #首页所在文件夹 index index.html index.htm; } location /api/ { proxy_pass http://127.0.0.1:3000; # 将/api/开头的url转向该域名 rewrite "^/api/(.*)$" /$1 break; 最终url中去掉/api前缀 } }2.7 重载nginx,浏览

nginx -s reload

3000端口的服务器要打开

2.8 vue中history模式的服务器端配置

vue中设置history模式

const router = new VueRouter({ base: process.env.BASE_URL, routes, mode: 'history'})

修改nginx的conf/nginx.conf

try_files $uri $uri/ /index.html;

代码如下:

server { listen 80; #nginx服务器端口 server_name localhost; #nginx域名 location / { root dist; #首页所在文件夹 index index.html index.htm; try_files $uri $uri/ /index.html; } location /api/ { proxy_pass http://127.0.0.1:3000; # 将/api/开头的url转向该域名 rewrite "^/api/(.*)$" /$1 break; //最终url中去掉/api前缀 }}
本文链接地址:https://www.jiuchutong.com/zhishi/280028.html 转载请保留说明!
下一篇链接:https://www.jiuchutong.com/zhishi/280029.html
免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

鄂ICP备2023003026号

友情链接: 武汉网站建设 电脑维修 湖南楚通运网络