vue在开发阶段解决跨域问题可以在vue.config.js里面配置:
module.exports = {
devServer: {
host:"localhost",
prot:"8080",
proxy: {
'/api': {
//以'/bpi'开头的请求会被代理进行转发
target: 'http://localhost:8081',
//服务端地址和端口http://192.168.2.1:8081
changeOrigin: true
}
}
}
}
我遇到的问题:需要切换环境的时候需要重新编译整个项目(vue.config.js貌似不会被hot-loader(热更新),且vue.config.js是被require引入的,运行时带有缓存所以修改vue.config.js不会监听到文件的变化)
解决方案:dev.config.js这个文件主要是对代理的编写,用回调函数修改API_URL这个值从而改变代理的target,changeEnv.js这个文件主要是对env.js这个文件的监听当env.js发生改变时调用回调函数返回修改后的值给dev.config.js.
vue.config.js文件如下
const isDev = process.env.NODE_ENV === 'development'
module.exports = {
devServer: isDev ? require('./dev.config') : null
}
dev.config.js文件如下
const { changeEnv } = require('./changeEnv.js')
let API_URL = 'http://192.168.60.11:300'
changeEnv((config) => {
console.log(config, 'config')
API_URL = config.url
})
const proxy = {
'/api': {
target: API_URL,
pathRewrite: {
'/api': '/'
}
}
}
for (const key in proxy) {
if (!proxy[key].pathRewrite) {
proxy[key].pathRewrite = {
'/api': '/'
}
}
Object.assign(proxy[key], {
// 使用router覆盖target
router: () => API_URL,
// https://github.com/chimurai/http-proxy-middleware/tree/v0.21.0#http-proxy-events
onProxyRes(proxyRes, req, res) {
proxyRes.headers['api-url'] = API_URL
}
})
}
module.exports = {
host: 'localhost',
port: 8080,
proxy
}
changeEnv.js文件如下
const fs = require('fs-extra')
exports.changeEnv = (callBack) => {
fs.watch('./env.js', (c) => {
if (c === 'change') {
callBack(getConfig())
return false
}
})
callBack(getConfig())
}
function getConfig() {
delete require.cache[require.resolve('./env.js')]
const config = require('./env.js')
return config
}
env.js文件如下
module.exports = {
url: 'http://192.168.60.11:3000'
}