美文网首页
webpack代理解决跨域

webpack代理解决跨域

作者: marioplus12 | 来源:发表于2018-10-13 19:12 被阅读0次

最近在学习vue,遇到了跨域问题,大概是这样

image.png

百度了一波发现webpack可以解决这个问题。

首先打开webpack的配置文件webpack.config.js,找到devServer节点,添加proxy属性即可。

完成是这个样子:

  devServer: {
    historyApiFallback: true,
    hot: true,
    inline: true,
    stats: { colors: true },
    // prot:8080,
    proxy: {
      '/api': {
        target: 'http://localhost:8081',
        pathRewrite: { '^/api': '/api' },
        changeOrigin: true
      },
      '/163': {
        target: 'http://music.163.com',
        pathRewrite: { '^/163': '' },
        changeOrigin: true
      }
    }

再看看请求的代码:

      var url
      // url = 'http://music.163.com/api/playlist/detail?id=37880978'
      // url='http://localhost:8081/api/playlist/19723756'
      url = '/api/playlist/19723756'
      // url = '/163/api/playlist/detail?id=37880978'
      Axios.get(url)
        .then(function(response) {
          console.log(response);
        })
        .catch(function(error) {
          console.log(233);
        });
      // console.log(1);
    }

我配置了两个代理

  1. 所有url为/api开头的都会被代理成http://localhost:8081/api/...
  2. 所有url为/163开头的都会被代理成http://music.163.com/api/...
  • 区别:
    两个代理的区别在于pathRewrite,这里可以理解成这样:
    1. 首先匹配到指定的开头(/163)
    2. 替换url:'http://music.163.com' + url.replace(/^\/163/,'')

特别提醒:

  • 修改完一定要重启!
  • 修改完一定要重启!
  • 修改完一定要重启!

相关文章

网友评论

      本文标题:webpack代理解决跨域

      本文链接:https://www.haomeiwen.com/subject/tsxaaftx.html