vue下跨域設置

一、在使用vue開發的時候常常要涉及到跨域的問題,其實在vue cli中是有咱們設置跨域請求的文件的。css

二、當跨域沒法請求的時候咱們能夠修改工程下config文件夾下的index.js中的dev:{}部分。
dev: {vue

env: require('./dev.env'),
    port: 8080,
    autoOpenBrowser: false,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
        '/api': {
            target: 'http://api.douban.com/v2',
            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
}

將target設置爲咱們須要訪問的域名。webpack

三、而後在main.js中設置全局屬性:git

Vue.prototype.HOST = '/api'

四、至此,咱們就能夠在全局使用這個域名了,以下:github

var url = this.HOST + '/movie/in_theaters'
    this.$http.get(url).then(res => {
      this.movieList = res.data.subjects;
    },res => {
      console.info('調用失敗');
    });
相關文章
相關標籤/搜索