1、需求说明
在前后端分离开发中,前端发送ajax请求因为受到了浏览器同源策略的限制,会出现跨域的问题,在Vue项目中使用代理请求解决跨域问题。
如果使用vue/cli 4.x以上版本创建的Vue项目,在项目的根目录中创建 vue.config.js
配置文件。
2、代码实现
在Vue项目根目录创建 vue.config.js
配置文件,配置代码如下:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000', //服务端地址
ws: true,
changeOrigin: true, // 允许跨域
pathRewrite: {
'^/api': '' // 标识替换,使用 '/api' 代替真实的接口地址
}
}
}
}
}
使用axios请求代码:
// 使用 '/api' 代替真实接口地址
// 真实地址为 http://localhost:3000/users/find
this.$axios.get('/api/users/find').then(res=>{
console.log(res)
})
代理配置的官方API地址: https://cli.vuejs.org/zh/config/#devserver-proxy
3、上线 nginx
配置
vue-cli 设置代理后,上线时也需要配置代理,以下以 nginx 为例,使用宝塔可视化操作更方便
http {
server {
listen 8081;
server_name localhost 127.0.0.1 10.20.11.153; # 站点域名
location / {
root ../road_net_ui;
index index.html index.htm;
}
location /api {
proxy_pass http://10.20.11.153:1026;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
location /webhdfs {
proxy_pass http://10.20.10.171:9870;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
}
}