Flask解決跨域
問題:
網頁上(client)有一個ajax請求,Flask sever是直接返回 jsonify。
然后ajax就報錯:No 'Access-Control-Allow-Origin' header is present on the requested
原因:
ajax跨域訪問是一個老問題了,解決方法很多,比較常用的是JSONP方法,JSONP方法是一種非官方方法,而且這種方法只支持GET方式,不如POST方式安全。
即使使用jquery的jsonp方法,type設為POST,也會自動變為GET。
官方問題說明:
“script”: Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, “_=[TIMESTAMP]“, to the URL unless the cache option is set to true.Note: This will turn POSTs into GETs for remote-domain requests.
如果跨域使用POST方式,可以使用創建一個隱藏的iframe來實現,與ajax上傳圖片原理一樣,但這樣會比較麻煩。
因此,通過設置Access-Control-Allow-Origin來實現跨域訪問比較簡單。
例如:客戶端的域名是www.client.com,而請求的域名是www.server.com
如果直接使用ajax訪問,會有以下錯誤
XMLHttpRequest cannot load http://www.server.com/xxx. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.client.com' is therefore not allowed access.
解決
在被請求的Response header中加入header,
一般是在Flask views.py
方法一:
@app.after_request def cors(environ): environ.headers['Access-Control-Allow-Origin']='*' environ.headers['Access-Control-Allow-Method']='*' environ.headers['Access-Control-Allow-Headers']='x-requested-with,content-type' return environ
方法二:
from flask import Flask, request, jsonify, make_response @app.route('/login', methods=['POST', 'OPTIONS']) def login(): username = request.form.get('username') pwd = request.form.get('pwd') if username == 'h' and pwd == '1': res = make_response(jsonify({'code': 0,'data': {'username': username, 'nickname': 'DSB'}})) res.headers['Access-Control-Allow-Origin'] = '*' res.headers['Access-Control-Allow-Method'] = '*' res.headers['Access-Control-Allow-Headers'] = '*' return res
方法三:沒試過
在Flask開發RESTful后端時,前端請求會遇到跨域的問題。下面是解決方法。Python版本:3.5.1
下載flask_cors包 pip install flask-cors 使用flask_cors的CORS,代碼示例 from flask_cors import * app = Flask(__name__) CORS(app, supports_credentials=True)