Vue代理,解决跨域问题

vue代理

使用vue时,经常遇到使用npm run serve后,与后端出现跨域问题,获取不到数据,其中一个解决方法,就是在前端,vue中开启代理proxy。

vue.config.js文件:

module.exports = {
  devServer: {
    proxy: {
      '/': {
        target: 'https://demo.com',
        secure: true,
        changeOrigin: true
      },
      '/api/': {
        target: 'http://test.com', //  接口路径
        ws: true, // 如果要代理websockets,配置该参数
        secure: false, // 如果接口为https,需要配置该参数
        changeOrigin: true, // 是否跨域
        pathRewrite: { // 改写接口请求地址,把/api改为/
          '^/api': '/'
        }
      }
    }
  }
}

配置后,请求地址会出现对应的变化:

原本的配置请求:

axios.get('https://demo.com/v0/find')
axios.get('http://test.com/v1/user/find')

配置后的配置请求:

axios.get('/v0/find')
axios.get('/api/v1/user/find')
原文地址:https://www.cnblogs.com/miao91/p/15710233.html