【VUE】一个简单常用的proxyTable配置

// 配置改动后需要重启生效 (运行npm run dev)
proxyTable: {

  // 所有 /api请求的路由会走这个代理
  '/api': {
    changeOrigin: true, //跨域
    target: 'http://172.16.0.107:1338'
  },

  // 所有 /ywapi请求的路由会走这个代理
  '/ywapi': {
    changeOrigin: true,
    target: 'http://127.0.0.1:7001',
    //重写路径
    pathRewrite: {
      '^/ywapi': '/abc/xxx' //例如 /api/getuser或被重写为 /ywapi/getuser
    },
    onProxyReq: function (proxyReq, req, res) {
      //实在不知道代理后的路径,可以在这里打印出出来看看
      console.log("原路径:" + req.originalUrl, "代理路径:" + req.path)
    }
  }
},

设置地址方式如下:

位置: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/save/index', {}, {
    },{}).then(function (response) {
      // 这里是处理正确的回调
      console.log(response)
      // this.articles = response.data["subjects"] 也可以
    }, function (response) {
      // 这里是处理错误的回调
      console.log(response)
    });
  }

可以看到我们的URL地址

会被映射为:http://127.0.0.1:3000/save/index

    '^/api': '/api'    这种接口配置出来     http://xxx:8080/api/save/index
          // 2  ^/api': '/' 这种接口配置出来     http://xxx:8080/save/index

即可解决跨域
接口地址原本是 /save/index,但是为了匹配代理地址,在前面加一个 /api, 因此接口地址需要写成这样的即可生效 /api/save/index。

注意: ‘/api’ 为匹配项,target 为被请求的地址,因为在 ajax 的 url 中加了前缀 ‘/api’,而原本的接口是没有这个前缀的,所以需要通过 pathRewrite 来重写地址,将前缀 ‘/api’ 转为 ‘/’。如果本身的接口地址就有 ‘/api’ 这种通用前缀,就可以把 pathRewrite 删掉。

你可能感兴趣的:(【VUE】一个简单常用的proxyTable配置)