Vue设置proxyTable实现跨域

版权声明:Callback_heaven©版权所有 https://blog.csdn.net/weixin_41564885/article/details/80302005

Vue与node.js项目中遇到的跨域问题,记录下解决方案:

       在项目中我的node提供的api为:

    127.0.0.1:3000/toutiao/seltoutiaoimg

众所周知,Vue默认端口为8080,故详情求node.js的API需要通过跨域实现

Vue中也提供了设置跨域的文件,下面是例子:

设置地址方式如下:

位置:config->index.js中

proxyTable: {
  '/api': {
    target: 'http://127.0.0.1:3000',
    changeOrigin: true,
    pathRewrite: {
      '^/api': ''
  }
    }
  },

这里的/api被映射为http://127.0.0.1:3000

Vue中的请求:

mounted: function () {
    this.$http.get('/api/toutiao/seltoutiaoimg', {}, {
    },{}).then(function (response) {
      // 这里是处理正确的回调
      console.log(response)
      // this.articles = response.data["subjects"] 也可以
    }, function (response) {
      // 这里是处理错误的回调
      console.log(response)
    });
  }

可以看到我们的URL地址

会被映射为:http://127.0.0.1:3000/tutiao/seltoutiaoimg

即可解决跨域

猜你喜欢

转载自blog.csdn.net/weixin_41564885/article/details/80302005