# Vue Axios CORS Policy : No 'Access-Control-Allow-Origin'
:::info
先簡單紀錄一下,有機會再補的詳細一點 QQ
:::
### 前情提要
透過 Vue CLI 建立了一個專案做完前端後,想要去連接後端 ( Python )。
Python 的部分用 Flask 去建 Web API,Vue 則是用 axios 去呼叫。
### 錯誤 Error
用 axios 去呼叫 API 會噴以下的錯誤:
:::danger
Access to XMLHttpRequest at 'http://...' from origin 'http://...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
:::
* axios 的 code
``` vue=
axios.get('http://..') // 要呼叫的 API
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err.response);
});
```
### 解決方法
要在後端 ( server 端 ) 的部分設定 header
> 在 client 端設定是沒有用的,所以 vue 的程式碼不需要改動
* Python
```python=
@app.route('/api', methods=['GET'])
def api():
res = flask.Response("...")
res.headers['Access-Control-Allow-Origin'] = '*' # 重點是這行 !!!
res.data = json.dumps(data) # 要傳送的資料
return res
```
### 警告 Warning
使用 Vue CLI 的 **Network** URL 會跳出以下警告:
:::warning
[Deprecation] The website requested a subresource from a network that it could only access because of its users' privileged network position. These requests expose non-public devices and servers to the internet, increasing the risk of a cross-site request forgery (CSRF) attack, and/or information leakage. To mitigate these risks, Chrome deprecates requests to non-public subresources when initiated from non-secure contexts, and will start blocking them in Chrome 92 (July 2021). See https://chromestatus.com/feature/5436853517811712 for more details.
:::
### 解決辦法
run Vue CLI 時,terminal 會出現以下資訊:
```
App running at:
- Local: http://localhost:8080/
- Network: http://192.168.100.100:8080/
```
使用 **Local** 的 URL,就不會跳出以上警告了。
### Reference
- [輕鬆學習 Python:使用 Flask 創建 Web API](https://medium.com/datainpoint/flask-web-api-quickstart-3b13d96cccc2)
- [Stack Overflow - Vue Axios CORS policy: No 'Access-Control-Allow-Origin'](https://stackoverflow.com/questions/55883984/vue-axios-cors-policy-no-access-control-allow-origin/67547984#67547984)
- [Stack Overflow - How do I set response headers in Flask?](https://stackoverflow.com/questions/25860304/how-do-i-set-response-headers-in-flask)