Flask解决跨域

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)



猜你喜欢

转载自www.cnblogs.com/hanbowen/p/9899088.html