【发布时间】:2020-07-08 08:47:09
【问题描述】:
我在pythonanywhere.com 上托管了一个应用程序。如果发送的数据不包含data 属性,则抛出 400 错误,否则返回响应数据。这是服务器的 Flask 代码:
@app.route('/api', methods=['POST'])
def get_post():
if not request.json or not 'data' in request.json:
abort(400)
data = request.json['data']
# do something with the data...
return jsonify({'response': str(data)}), 200
我的应用程序的前端部分应该发送一个带有数据的 POST 请求并获得响应。我正在尝试使用fetch,但尽管我发送带有data 对象的JSON 对象,但它会出现400 错误:
function sendData(value) {
data = { 'data': value };
fetch('http://' + appUrl, {
method: 'POST',
headers: {
'content-type': 'application/json',
},
mode: 'no-cors',
body: JSON.stringify(data),
})
.then(data => { return data.json() })
}
我也尝试使用XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open("POST", 'http://' + appUrl, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(data);
但我不知道如何禁用 CORS 并获取响应数据。
【问题讨论】:
-
如果是 CORS 问题,最好检查您的服务器,假设您正在尝试从不同的来源(
pythonanywhere.com除外)发出 http 请求,发现此 flask-cors.readthedocs.io/en/latest。希望这可以帮助 -
@noobHere,非常感谢,您的解决方案对我有用。我使用 fetch 没有 no-cors 模式并且成功地得到了响应。您可以给出答案,我会检查它作为解决方案。
-
很高兴 :)
标签: javascript post request fetch