1. 程式人生 > >webpack+axios配置代理進行跨域訪問資料

webpack+axios配置代理進行跨域訪問資料

在學習vue的axios時,訪問自己的本地資料出現了跨域問題,如下圖
這裡寫圖片描述
主要程式碼有

var root = 'http://172.16.188.107:8080/im'
、、、
getData() {
   this.$api.get('/data1.json', null, r => {     
    console.log(r);
    }, f => {
     console.log(f);
     })
  }

如何解決這個問題呢?其實非常好辦,那就是將介面代理到本地。

配置webpack將介面代理到本地

其實,vue-cli腳手架工具,已經充分的考慮到這個問題,我們只要進行簡單的設定,就能實現我們的目的。
我們開啟config/index.js檔案,找到以下程式碼:

 dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
    },

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: true, errorOverlay: true, notifyOnErrors: true, poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- // Use Eslint Loader? // If true, your code will be linted during bundling and // linting errors and warnings will be shown in the console.
useEslint: true, // If true, eslint errors and warnings will also be shown in the error overlay // in the browser. showEslintErrorsInOverlay: false, /** * Source Maps */ // https://webpack.js.org/configuration/devtool/#development devtool: 'cheap-module-eval-source-map', // If you have problems debugging vue-files in devtools, // set this to false - it *may* help // https://vue-loader.vuejs.org/en/options.html#cachebusting cacheBusting: true, cssSourceMap: true },

其中,proxyTable:{},這一行,就是給我們配置代理的。
根據我們要訪問的介面,我們把這裡調整為:

    proxyTable: {
      '/im':{
        target: 'http://172.16.188.107:8080', // 你介面的域名
        //secure: false,    //如果是https介面,需要配置這個引數
        changeOrigin: false,
      }
    }

配置完以後再修改一下之前上面的程式碼,就可以了。

var root = '/im'

這裡寫圖片描述