按照百度尝试了一晚上,都是在 config/index.js  文件中配置跨域,但是 vue2.x 的版本并不适用,页面无法取得配置文件中的跨域路径。

        最后找到大佬:vue2.6.11 版本解决跨域_海马区的博客-CSDN博客

        总结一下:vue2 需要在项目根目录下新建 vue.config.js 进行跨域配置。

vue.config.js 配置

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000', // 跨域地址
        ws: true,
        changOrigin: true, //允许跨域
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

 

项目开发中发现config/index配置对于使用vue3脚手架生成的vue2项目有效

config/index配置

module.exports = {
    dev: {
        // Paths
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: {
          '/api': {
            target: '需跨域地址',
            changeOrigin: true,
            pathRewrite: {
              '^/api': ''
            }
          }
        }
}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐