vue-cli+axios的跨域访问

1、在使用vue开发的时候经常要涉及到跨域的问题,其实在vue cli中是有我们设置跨域请求的文件的。
2、当跨域无法请求的时候我们可以修改工程下config文件夹下的index.js中的dev:{}部分。

dev: {

env: require('./dev.env'),
    port: 8080,
    autoOpenBrowser: false,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
        '/api': {
            target: '所需访问的域名',
            changeOrigin: true,
            pathRewrite: {
                '^/api': ''
            }
        }
    },
    // 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
}
3、然后在main.js中设置全局属性:
Vue.prototype.HOST = '/api'
4、至此,我们就可以在全局使用这个域名了,如下:
var url = this.HOST + '/movie/in_theaters'
    this.$http.get(url).then(res => {
      this.movieList = res.data.subjects;
    },res => {
      console.info('调用失败');
    });

参考来源:https://segmentfault.com/a/1190000008629361

发布了21 篇原创文章 · 获赞 2 · 访问量 6503

猜你喜欢

转载自blog.csdn.net/weixin_43386443/article/details/84098549