前后端分离项目跨域问题解决
开发环境 | 生产环境 | |
---|---|---|
后台主导 | CORS | CORS |
前端主导 | proxy代理 | nginx代理 |
vue.config.js
module.exports = {
devServer: {
proxy: "后台接口地址"
}
}
配置完proxy之后,我们请求接口的地址需要是当前前端服务的地址
http://localhost:3000 -> http://localhost:8080
既然要请求自己的地址,那么就没有必要写localhost:8080 直接写/即可
http://localhost:8080/api/banners -> /api/banners
如果使用代理,那么就没有必要使用.env中去进行我们对应的接口地址的配置。因为不管在什么环境下,都是请求当前前端服务器地址
如果使用CORS 则需要在build时根据.env去请求不同环境的服务器地址, 如果使用代理,则不需要配置不同地址,全部都使用/api/xxx
的形式
后台配置CORS
前端需要在axios的配置中配置baseURL。前提需要先配置好.env环境变量文件
.env.development
新建开发环境的env文件
VUE_APP_BASEURL=http://开发环境接口地址
.env.production
新建生产环境的env文件
VUE_APP_BASEURL=http://生产环境接口地址
配置axios
const _axios = axios.create({
baseURL: process.env.VUE_APP_BASEURL
})
服务器代理
如果使用代理,则前端不需要再配置BASEURL,因为请求全部走的前端服务(代理)
接口地址直接写 “/xxx” 相关的内容即可
开发环境配置
vue.config.js
如果只有一个后台
module.exports = {
devServer: {
proxy: "http://开发环境后台地址",
}
}
如果有多个后台接口
module.exports = {
devServer: {
proxy: {
"/自定义前端请求时前缀": {
target: "http://开发环境后台地址",
pathRewrite: {
"^/自定义前端请求时前缀": "/后台真实前缀"
}
},
"/自定义前端请求时前缀": {
target: "http://开发环境后台地址",
pathRewrite: {
"^/自定义前端请求时前缀": "/后台真实前缀"
}
}
}
}
}
注意,在请求时,不需要配置axios的baseURL,也不需要添加任何的域名
生产环境中
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://要代理的服务器地址(生产服务器地址);
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}