天天看點

vue使用axios插件請求通路API遇到的跨域問題。

API位址:

http://www.caiji.me/api/test (本地開發的接口位址,通路接口會傳回字元串“接口測試”;
      

axios請求方法:引入元件 axios後,編寫請求接口方法:

mounted() {
    axios.get('http://www.caiji.me/api').then(function (res) {
        console.log(res);
    });
}      

本地 http://localhost:8080/ 運作項目時,在執行到請求時報錯顯示:

Access to XMLHttpRequest at 'http://www.caiji.me/api' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

vue使用axios插件請求通路API遇到的跨域問題。

很明顯,屬于跨域問題。此處不探讨其他解決方案。

下面說一下自己的解決方案。

本人初學vue腳手架版本為4.4.6 ,在vue.config.js 添加如下标紅代碼:

module.exports = {
  outputDir: '../public'
  , devServer: {
    proxy: {
      '/api': {
        target: 'http://www.caiji.me',
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '^/api':  '/api',
        }
      }
    }
  }
}      

同時将vue中請求修改為:

axios.get('/api/test').then(function (res) {
    console.log(res);
});
      

修改完成後,重新運作一下項目。即可完成跨域請求操作。

請求結果如下:

vue使用axios插件請求通路API遇到的跨域問題。

繼續閱讀