webpack开发环境处理跨域的方法就是配置
devServer
的proxy,在服务器接口的nginx根据域名有多个分发的时候,会报404
- 通用配置:
cinfig-index.js
(基于vue-cli 2.x)
dev: {
proxyTable: {
'/dev': {
target: "http://xxx.xxxxxx.xx", // 转发到的服务器的域名/IP
pathRewrite: {
"^/dev": "" // 重写path
},
}
},
原理:
webpack
使用的是http-proxy-middleware
的包,找到配置

进而去看
http-proxy
的源码,打印请求配置:

看出:host
是请求的地址,但在headers里,hosth还是localhost:8082
,此时请求是报404的,所以去找服务端的错误日志

nginx从请求头里找到的host为
localhost
,和转发的配置规则不一样,就走到默认的路径里去里,自然找不到资源
解决办法: changeOrigin: true
http-proxy
的源码里关于请求头的配置:

该项是需要配置的:config-index.js
dev: {
proxyTable: {
'/dev': {
target: "http://xxx.xxxxxx.xx", // 转发到的服务器的域名/IP
pathRewrite: {
"^/dev": "" // 重写path
},
changeOrigin: true // 配置请求头
}
},
再来看请求头信息:

就改为配置的域名了。
这时候就请求通过了。
小结
其实还是http协议的内容,没有出现bug就会忽视细节。多巩固原理吧。
网友评论