1. 程式人生 > >【原創】Vue.js 中 axios 跨域訪問錯誤

【原創】Vue.js 中 axios 跨域訪問錯誤

1、假如訪問的介面地址為 http://www.test.com/apis/index.php  (php api 介面)

2、而開發地址為http://127.0.0.1:8080,當axios發起請求時,出現如下錯誤:

Failed to load http://www.test.com/apis/index.php?&act=login: The value of the 'Access-Control-Allow-Origin' headerin the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://127.0.0.1:8080' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

解決方法:
1、修改config/index.js, 修改 proxytable

    proxyTable: {
      '/apis': {
          target: 'http://www.test.com/apis/',  // 介面地址
          changeOrigin: true,  
          pathRewrite: {
              '^/apis': ''   //需要rewrite重寫的,
          }              
      }
    },


2、重啟 npm run dev    (很重要,否則不生效)

3、訪問介面(訪問時通過代理轉發的,有點類似APACHE的urlrewrite,不需要完整http://www.test.com網址。)

                this.$api.get('/apis/index.php?act=login', {
                    "act": "login"
                  }, response => {
                       //success
                  },error => {
                       //error
                  }
                );

  

 

大功告成,成功解決錯誤,另外:PHP端不需要做任何的header設定,網上很多教程胡說八道,根本不能實現跨域