今天因為同學專案的問題,重新看了一下之前代碼的跨域問題的解決方式,也查閱了很多資料,整理記錄一下,
問題:
當客戶端向服務器端請求ajax服務時,如果客戶端和服務器端域名不一致,就會出現跨域問題,ajax報錯:No 'Access-Control-Allow-Origin' header is present on the requested ,
解決跨域(全域配置):
1、通過引入Cors包解決跨域:
from flask import Flask from flask_cors import CORS app = Flask(__name__) CORS(app) if __name__ == "__main__": app.run()
CORS引數說明
| 引數 | 型別 | Head欄位 | 說明 |
|---|---|---|---|
| resources | 字典、迭代器或字串 | 無 | 全域配置允許跨域的API介面 |
| origins | 串列、字串或正則運算式 | Access-Control-Allow-Origin | 配置允許跨域訪問的源,*表示全部允許 |
| methods | 串列、字串 | Access-Control-Allow-Methods | 配置跨域支持的請求方式, 如:GET、POST |
| expose_headers | 串列、字串 | Access-Control-Expose-Headers | 自定義請求回應的Head資訊 |
| allow_headers | 串列、字串或正則運算式 | Access-Control-Request-Headers | 配置允許跨域的請求頭 |
| supports_credentials | 布林值 | Access-Control-Allow-Credentials | 是否允許請求發送cookie, false是不允許 |
| max_age | 整數、字串 | Access-Control-Max-Age | 預檢請求的有效時長 |
2、在被請求的Response header中加入header
from flask import Flask
def after_request(response): response.headers['Access-Control-Allow-Origin'] = request.headers.get('Origin') or 'http://127.0.0.1:9528' response.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE' response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization,Accept,Origin,Referer,User-Agent' response.headers['Access-Control-Allow-Credentials'] = 'true' return response app = Flask(__name__) app.after_request(after_request) if __name__ == "__main__": app.run()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/192016.html
標籤:其他
上一篇:Qt5+MSVC2015 32位編譯器報錯: qalgorithms.h: error C3615 不會生成常數運算式
