vue项目中使用proxy解决跨域

在使用vue开发项目的时候,总会遇到跨域问题,可以在打包的时候使用proxy反向代理解决跨域问题。

vue-cli2配置如下:

找到config文件夹下的index.js

dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'http://moby.xbotech.com',//填写A真实的后台接口
        changeOrigin: true,//允许跨域
        secure: false,
        pathRewrite: {//重写请求路径
          '^/api': ''
        }
      }
},

  请求路径

const service = axios.create({
  baseURL: 'api', //process.env.VUE_APP_BASE_API,
  // baseURL: process.env.VUE_APP_BASE_API, //api, 
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 300000 // request timeout
  
})

  vue-cli3版本以上,需要自己创建vue.config.js文件,在这个文件中自己配置

module.exports = {
    devServer: {       host: '0.0.0.0', // 允许外部ip访问
        port: 9080, // 端口
        https: false, // 启用https
        proxy: {
          '/api': {
            target: 'http://moby.xbotech.com/api/login',
            changeOrigin: true,
            secure: false,
            pathRewrite: {
              '^/api': '/api'
            }
          }
        }
    }
}

  使用axios发送请求

aixos.get('/api/list')

  总结:无论是那种方式创建的项目, '/api' 为匹配项,target 为被请求的地址,因为在 ajax 的 url 中加了前缀 '/api',而原本的接口是没有这个前缀的,所以需要通过 pathRewrite 来重写地址,将前缀 '/api' 转为 '/'。如果本身的接口地址就有 '/api' 这种通用前缀,就可以把 pathRewrite 删掉。

转自:https://www.cnblogs.com/zmyxixihaha/p/12786776.html

原文地址:https://www.cnblogs.com/llllpzyy/p/15151013.html