Vue.js 中 axios 跨域訪問錯誤問題及解決方法
1、假如訪問的接口地址為 http://www.test.com/apis/index.php (php api 接口)
2、而開發(fā)地址為http://127.0.0.1:8080,當(dāng)axios發(fā)起請求時,出現(xiàn)如下錯誤:
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、訪問接口(訪問時通過代理轉(zhuǎn)發(fā)的,有點類似APACHE的urlrewrite,不需要完整http://www.test.com網(wǎng)址。)
this.$api.get('/apis/index.php?act=login', {
"act": "login"
}, response => {
//success
},error => {
//error
}
);
大功告成,成功解決錯誤,另外:PHP端不需要做任何的header設(shè)置,網(wǎng)上很多教程胡說八道,根本不能實現(xiàn)跨域。
總結(jié)
以上所述是小編給大家介紹的Vue.js 中 axios 跨域訪問錯誤問題及解決方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
圖文講解用vue-cli腳手架創(chuàng)建vue項目步驟
本次小編給大家?guī)淼氖顷P(guān)于用vue-cli腳手架創(chuàng)建vue項目步驟講解內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。2019-02-02
一文搞懂Vue3中toRef和toRefs函數(shù)的使用
這篇文章主要為大家介紹了Vue3中toRef和toRefs函數(shù)的使用方法,文中通過示例為大家進行了詳細的講解,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-07-07
2分鐘實現(xiàn)一個Vue實時直播系統(tǒng)的示例代碼
這篇文章主要介紹了2分鐘實現(xiàn)一個Vue實時直播系統(tǒng)的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06

