【发布时间】:2019-09-24 08:34:42
【问题描述】:
我正在使用烧瓶为区块链项目创建一些端点。我需要接受来自 ajax 客户端的 json 数据。由于它是跨平台,我正在使用烧瓶 cors 。但我似乎无法找到解决方案。它不工作
我已经试过了
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, origin = '*')
基本上我的客户端代码如下。
$.ajax({
url: 'http://localhost:8080/ratings/new',
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: json1,
crossDomain: true,
xhrFields: {
withCredentials: true
},
processData: false,
beforeSend: function (xhr) {
//xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
success: function (data, textStatus, jQxhr)
{
$('body').append(data);
console.log(data);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
在我的服务器上,我有一个端点
@app.route('/ratings/new', methods = ['POST','OPTIONS'])
def rating():
values = request.get_json()
if values == None:
return "No data received", 400
#ratings = values['rating']
index = blockchain.new_ratings(values)
response = {
'Message': f'New transaction will be added to the block {index}',
}
response = jsonify(response)
response.headers.add('Access-Control-Allow-Origin','*')
return response, 201
在服务器端我没有收到所需的数据,在客户端我收到以下错误。
Access to XMLHttpRequest at 'http://localhost:8080/ratings/new' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
请帮我解决这个问题。提前致谢。
【问题讨论】:
-
在您的 Flask 代码中添加
response.headers.add('Access-Control-Allow-Credentials', true)。并尝试。欲了解更多信息,请查看此html5rocks.com/en/tutorials/cors 美丽的文档。
标签: json ajax python-3.x flask flask-cors