error-has been blocked by CORS policy:

--

先前用Vue開發時,有遇過用axios呼叫API時,發生 xxx has been blocked by CORS poicy: No Access-Control-Allow-Origin header is present on the requested resource.

解決方案

1.後端去改回傳的header
加上以下內容(不過有時後端不會想理你,主管又不夠力時此法無效XD)

header(‘Access-Control-Allow-Origin’, ‘*’) 
header(‘Access-Control-Allow-Methods’, ‘*’)
header(‘Access-Control-Allow-Headers’, ‘Origin, Methods, Content-Type, Authorization’)
header(‘Access-Control-Allow-Credentials’, true);

2.前端自己改
用vue-cli,建立項目,找到config/index.js檔案加上以下內容

module.exports = {
dev:{
ProxyTable: {
'/data': { // 自訂 local 端的位置
target: 'http://data.taipei/', // 遠端 URL Domain
changeOrigin: true,
pathRewrite: {
'^/data': ''
}
}
}
}

Ref:
https://blog.csdn.net/weixin_44623040/article/details/94987738
https://ithelp.ithome.com.tw/questions/10199222

https://kuro.tw/posts/2017/06/07/%E5%A6%82%E4%BD%95%E5%9C%A8-Vue-CLI-%E5%BB%BA%E7%AB%8B%E7%9A%84%E9%96%8B%E7%99%BC%E7%92%B0%E5%A2%83%E5%91%BC%E5%8F%AB%E8%B7%A8%E5%9F%9F%E9%81%A0%E7%AB%AF-RESTful-APIs/

--

--

Jameskrauser Lee
Jameskrauser Lee

Written by Jameskrauser Lee

For the last few years. i was involved mostly in the development of Automatic Fare collection system for the Chennai Metro. Familiar with C++ and iOS.

No responses yet