devServer changeOrigin属性是修改后端服务器接收到的 headers 里的 Host 属性
vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({transpileDependencies: true,devServer: {proxy: {'/api': {target: 'http://localhost:3000',changeOrigin: false}}}
})
后端 headers
{'x-forwarded-host': '192.168.0.111:8080','x-forwarded-proto': 'http','x-forwarded-port': '8080','x-forwarded-for': '192.168.0.111',referer: 'http://192.168.0.111:8080/',connection: 'close',origin: 'http://192.168.0.111:8080','content-length': '27','content-type': 'application/json','accept-encoding': 'gzip, deflate','accept-language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',accept: 'application/json, text/plain, */*','user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/116.0',host: '192.168.0.111:8080'
}
改为 hangeOrigin: true 后 headers
{'x-forwarded-host': '192.168.0.111:8080','x-forwarded-proto': 'http','x-forwarded-port': '8080','x-forwarded-for': '192.168.0.111',referer: 'http://192.168.0.111:8080/',connection: 'close',origin: 'http://192.168.0.111:8080','content-length': '27','content-type': 'application/json','accept-encoding': 'gzip, deflate','accept-language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',accept: 'application/json, text/plain, */*','user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/116.0',host: 'localhost:3000'
}
可以看到 host 由 host: '192.168.0.111:8080' 变为后端服务器地址 host: 'localhost:3000'
通过上面的探究,基本可以得出以下结论:
- changeOrigin 配置项用来修改 host header,而非 origin header
- Host header 用来处理虚拟主机的问题,和跨域无关
- 一般情况下,设置代理时可以忽略这个配置项,保持默认即可
- 特殊情况下,很可能后端服务就用 host 做校验了,此时根据实际情况去设置