如果是前台解决跨域问题 可使用 proxy代理方式
<!-- a b c
前台 a:localhost:8080 要请求后台 c :3000 的数据,但由于跨域 中间隔了一堵墙 b
但墙b既可以被a访问,也可访问c (b就是一个代理,想当于中介)
于是a 让 墙b(就是自己的服务器) 上面的8080 去请求c,把数据给b,b再给a
-->
1
开发环境中 新建 vue.config.js文件
//只有一个后台接口
module.exports = {
//如果未来项目 是以http://域名/文件名的方式访问 则要设置 publicPath
publicPath:"/文件名",
devServer: {
proxy: "http://开发环境后台地址",
}
}
//有多个后台接口
module.exports = {
devServer: {
proxy: {
"/自定义前端请求时前缀": {
target: "http://开发环境后台地址",
pathRewrite: {
"^/自定义前端请求时前缀": "/后台真实前缀"; 一定要写分号 (结束标记一定要写)
}
},
"/自定义前端请求时前缀": {
target: "http://开发环境后台地址",
pathRewrite: {
"^/自定义前端请求时前缀": "/后台真实前缀";
}
}
}
}
}
配置完成后,一个要重启vue项目
注意,在请求时,不需要配置axios的baseURL(因为会在vue.config.js自动代理),也不需要添加任何的域名
2
生产环境中
build之后,我们不再有nodejs服务器,只是静态页面(proxy设置只能针对开发环境)
生产环境需要配置nginx
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
# 只能有一个
# 没有使用history
index index.html index.htm;
# 使用了history
try_files $uri $uri/ /index.html;
}
# 配置代理
location /服务器前缀 {
proxy_pass http://要代理的服务器地址(生产服务器地址);
}
# 配置代理 需要进行rewrite
location /前端请求的前缀 {
rewrite ^/前端请求前缀/(.*)$ /后台接口真实前缀/$1 break;
proxy_pass http://要代理的服务器地址(生产服务器地址);
}
#eg:
location /demo {
rewrite ^/demo/(.*)$ /api/$1 break;
proxy_pass http://localhost:3000;
}
1283

被折叠的 条评论
为什么被折叠?



