vue中的跨域代理

在config文件夹中的index.js设置pxoxyTable

dev: {
    env: require('./dev.env'),
    port: process.env.PORT || 8088,
    autoOpenBrowser: false,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
        '/list': {
            target: 'https://jsonplaceholder.typicode.com/',//设置你调用的接口域名和端口号 别忘了加http
            changeOrigin: true,
            pathRewrite: {
                '^/list': '/' // 这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可
            }
        }
    },
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  }

在组件的js引用

const self = this;
      self.$axios.post('/list/posts').then((response) => { console.log(response.data); });

注意请求的地址是localhost:8080/list/posts/, 代理的是https://jsonplaceholder.typicode.com/list/posts
对于请求不到数据,如果代理设置正确,就是地址写错啦,如何验证是代理写错啦,还是请求地址写错了,用本地的ip替代要请求后台的ip地址
eg:http://localhost:8088/list/posts
代替https://jsonplaceholder.typicode.com/posts/看是否有数据
注意是/list/posts,而不是/posts

你可能感兴趣的:(vue,跨域,vue)