[Python] Sanic chrome XMLHttpRequest CORS Access-Control-Allow-Headers 問題

Python Sanic chrome CORS

使用sanic 框架 用vue-axiso發出請求在Chrome 的console 中報 Access to XMLHttpRequest at 'http://xxxxxxxx' from origin 'null' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. 和 'Access-Control-Allow-Origin' 跨域問題

導致在chrome中請求不到數據在firefox中可以,option請求後沒有發出post請求等問題....

主要是chrome的安全限制跨站請求需要同源,或者就需要在服務端設置返回頭以允許跨站請求。在sanic中,之間用中間件方法,對請求和返回進行統一添加頭,對post前的option預檢請求進行相應即可,具體代碼片段:

 

@app.middleware('request')
async def print_on_request(request):
    if request.method == 'OPTIONS':
        return response.json(None)  

@app.middleware('response')
async def prevent_xss(request, response):
    if 'X-Error-Code' not in dict(response.headers):
        response.headers['X-Error-Code'] = 0
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Headers"] = "X-Custom-Header,content-type"

 

參考資料:

    跨域資源共享 CORS 詳解 : http://www.ruanyifeng.com/blog/2016/04/cors.html 

    Sanic 中間件 和 監聽器 :https://sanic-cn.readthedocs.io/zh/latest/sanic/middleware.html#

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章