Solution to cross-domain problems in front-end and back-end separation projects
Development environment | Production Environment | |
---|---|---|
Backstage leader | CORS | CORS |
Front-end dominance | proxy proxy | nginx proxy |
vue.config.js
module.exports = {
devServer: {
proxy: "后台接口地址"
}
}
After configuring the proxy, the address of our request interface needs to be the address of the current front-end service
http://localhost:3000 -> http://localhost:8080
Since you want to request your own address, then there is no need to write localhost:8080 directly to write /
http://localhost:8080/api/banners -> /api/banners
If you use a proxy, then there is no need to use .env to configure our corresponding interface address. Because no matter what the environment, the current front-end server address is requested
If you use CORS, you need to request server addresses in different environments according to .env during build. If you use a proxy, you don’t need to configure different addresses, all of them are /api/xxx
in the form
Configure CORS in the background
The front end needs to configure baseURL in the axios configuration. Prerequisites need to configure the .env environment variable file first
.env.development
Create an env file for the development environment
VUE_APP_BASEURL=http://开发环境接口地址
.env.production
Create an env file for the production environment
VUE_APP_BASEURL=http://生产环境接口地址
Configure axios
const _axios = axios.create({
baseURL: process.env.VUE_APP_BASEURL
})
Server proxy
If a proxy is used, the front-end does not need to configure BASEURL, because the front-end service (proxy) is all requested
The interface address can be directly written "/xxx" related content
Development environment configuration
vue.config.js
If there is only one backstage
module.exports = {
devServer: {
proxy: "http://开发环境后台地址",
}
}
If there are multiple background interfaces
module.exports = {
devServer: {
proxy: {
"/自定义前端请求时前缀": {
target: "http://开发环境后台地址",
pathRewrite: {
"^/自定义前端请求时前缀": "/后台真实前缀"
}
},
"/自定义前端请求时前缀": {
target: "http://开发环境后台地址",
pathRewrite: {
"^/自定义前端请求时前缀": "/后台真实前缀"
}
}
}
}
}
Note that when requesting, there is no need to configure the baseURL of axios, nor add any domain names
In production
After the build, we no longer have a nodejs server, just a static page (proxy settings can only be aimed at the development environment)
The production environment needs to configure 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;
}
}