傻傻的npm run serve吗?还有其他方法换项目中的代理

发布时间 2023-05-24 10:50:38作者: 7c89
1.直接修改 封装的axios  host 使用浏览器跨域

2.
--------hostconfig.js--------
module.exports = {
    "target": "http://xxxxxx"   
};

---------vue.config.js----------
/*
   target: 'that must have a empty placeholder',
        // changeOrigin: true,
        // 每次发起http请求都会执行router函数
        router: () => (hotRequire('./hostconfig.js') || {}).target || '',    
*/


const hotRequire = modulePath => {
  // require.resolve可以通过相对路径获取绝对路径
  // 以绝对路径为键值删除require中的对应文件的缓存
  delete require.cache[require.resolve(modulePath)]
  // 重新获取文件内容
  const target = require(modulePath)
  return target
}

devServer: {
    hot: true,
    open: true, // 配置自动启动浏览器
    disableHostCheck: true, //webpack4.0 开启热更新  
    host: "xxx",
    port: "8080",
    proxy: {
      '/api': {
        target: 'that must have a empty placeholder',
        // changeOrigin: true,
        // 每次发起http请求都会执行router函数
        router: () => (hotRequire('./hostconfig.js') || {}).target || '',       
        pathRewrite: {
          '^/api': '',
        },
      },
    },
  },