Vue项目devServer proxy配置不生效的排查方法?-灵析社区

博学的学渣

关于跨域配置的问题 如图,我需要调用以下请求访问资源 ![image.png](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20240915/31f250e40287423f9a5eb6890a069566.png) vue.config.js的配置如下(主要是proxy的配置 const path = require('path') module.exports = { lintOnSave:false, runtimeCompiler: true, css: { loaderOptions: { scss: { additionalData:`@import "~@/assets/scss/global.scss";` } } }, chainWebpack: (config) => { //svg不编译 config.module .rule('svg') .exclude.add(path.join(__dirname, 'src/assets/svg')) .end() config.module .rule('icons')// 定义一个名叫 icons 的规则 .test(/\.svg$/)// 设置 icons 的匹配正则 .include.add(path.join(__dirname,'src/assets/svg'))// 设置当前规则的作用目录,只在当前目录下才执行当前规则 .end() .use('svg-sprite')// 指定一个名叫 svg-sprite 的 loader 配置 .loader('svg-sprite-loader')// 该配置使用 svg-sprite-loader 作为处理 loader .options({// 该 svg-sprite-loader 的配置 symbolId:'icon-[name]' }) .end() }, devServer:{ client:{ overlay: false }, proxy:{ '/hie':{ target:'http://192.168.17.77:7003', changeOrigin: true, } } }, } 可能是哪里配错了,但我看不出问题,希望有人能指出 ps:之前看到有帖子说vue2该配置项名为proxyTable,还有devServer应为dev,这两个我都试过了,前者提示没有该配置项 options has an unknown property 'proxyTable'. These properties are valid: object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? } ValidationError: Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. 后者为vue.config.js的提示: Invalid options in vue.config.js: "dev" is not allowed

阅读量:150

点赞量:0

问AI
你要明白代理转发的实现逻辑。就是把所有的请求,请求到你本地启动的代理服务器上,然后通过代理服务器去转发到目标服务器。 也就是你的网页中发起请求的 "url" 调整为当前项目("devServer")启动的地址。 比如说在控制台中输出的 "localhost:8899" 这样的地址。 "图片.png" (https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20240915/bd5c52f840eed3dc29ba50cfd7e8c67d.png) 那么在你的例子中请求的 "http://192.168.17.77:7003/hie/xxxx" 就需要调整为 "http://localhost:8899/hie/xxxx"。 这样才会通过本地的 "devServer" 去转发请求到你的目标服务("http://192.168.17.77:7003")上面。 *** 一般这样的调整我们都会在 "axios" 之类的 http 请求库中的 "baseURL" 去配置。 但是一般我们本地启动的时候 本机ip 和 端口号 可能并不一定是固定的,那么"baseURL" 就可以设置为 "/",让浏览器会自动按照当前页面中 "host" 拼接请求地址,而不是指定一个具体的 ip地址 或者 域名 。 所以 "devServer" 就可以这样配置: // vue.config.js const port = process.env.port || process.env.npm_config_port || 8000 // 端口 module.exports = { devServer: { host: '0.0.0.0', port: port, open: true, proxy: { // detail: https://cli.vuejs.org/config/#devserver-proxy '/hie': { target: 'http://192.168.17.77:7003', changeOrigin: true } }, disableHostCheck: true } } 然后如果你使用的是 "axios" 就可以这样设置。 // 创建axios实例 const service = axios.create({ baseURL: '/', timeout: 60000 })