Solve the front-end cross-domain problem proxy configuration
The same origin means that the protocol, domain name, and port must be the same, and any one of them will appear cross-domain
Reference article
[1] https://blog.csdn.net/tttttrrrhh/article/details/127685318 [
2] https://blog.csdn.net/X_W123/article/details/120369610?spm=1001.2014.3001.5506
^ means start of matching character
If I now want to request an interface on the backend, for example: http://www.aaabbbccc.com/login, how should we configure the proxy server?
operate:
// vue.config.js
devServer: {
//开启代理服务器
proxy:{
"/api": {
// /api是自行设置的请求前缀,按照这个来匹配请求,有这个字段的请求,就会走到代理来。
target: "http://www.aaabbbccc.com", // 需要代理的域名,目标域名,会替换掉匹配字段之前的路径
ws: false, // 是否启用websockets
changeOrigin: true, //是否跨域
pathRewrite: {
//重写匹配的字段,如果不需要放在请求路径上,可以重写为""
"^/api": ""
}
},
},
}
In the above configuration, I configured an /api, and only the path containing this request will go through the proxy, for example:
http://localhost:8080/api/login //This can go through the proxy
http://localhost:8080/login //This will not work
conversion steps
At this time, the request I sent is:
http://localhost:8080/api/login
http://localhost:8080/api/getlist
http://localhost:8080/api/user/hello
Encounter contains "/api" to start working
After processing through the target attribute of the agent , it is:
http://www.aaabbbccc.com/api/login
http://www.aaabbbccc.com/api/getlist
http://www.aaabbbccc.com/api/getlist
Replace /api with nothing through the pathRewrite attribute:
http://www.aaabbbccc.com/login
http://www.aaabbbccc.com/getlist
http://www.aaabbbccc.com/user/hello
diagram