flask cors问题解决

原文链接: https://blog.csdn.net/hwhsong/article/details/84959755

由于浏览器受同源策略的限制,在使用XMLHttpRequest对象进行跨域请求时,通常会报No 'Access-Control-Allow-Origin' header is present on the requested resource.错误,导致请求失败。
解决该问题的基本思路是使用CORS(Cross-Origin Resource Sharing)JSONP,具体到Flask场景,有以下三种方式。

使用flask内置的after_request()方法

app = Flask(__name__)

跨域支持

def after_request(resp):
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

app.after_request(after_request)

使用flask_cors模块

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)

CORS(app)

更多有关flask-cors模块的用法可参考:https://flask-cors.readthedocs.io/en/latest/

使用JSONP

from flask import Flask, request


# 获取回调函数名称
callback = request.args.get('callback')
# 支持JSONP,使用回调函数包裹实际要返回的JSON数据
return callback + '(' + json.dumps(resp_data) + ')'
发布了75 篇原创文章 · 获赞 25 · 访问量 1万+
原文链接: https://blog.csdn.net/hwhsong/article/details/84959755

由于浏览器受同源策略的限制,在使用XMLHttpRequest对象进行跨域请求时,通常会报No 'Access-Control-Allow-Origin' header is present on the requested resource.错误,导致请求失败。
解决该问题的基本思路是使用CORS(Cross-Origin Resource Sharing)JSONP,具体到Flask场景,有以下三种方式。

使用flask内置的after_request()方法

app = Flask(__name__)

猜你喜欢

转载自blog.csdn.net/gghhm/article/details/102708398