简体   繁体   English

发出正确的 POST 请求并获取响应数据

[英]Make a correct POST request and get response data

I have an application hosted on pythonanywhere.com .我有一个托管在pythonanywhere.com上的应用程序。 It throws a 400 error if sended data does not contain data property, otherwise it returns a response data.如果发送的数据不包含data属性,则抛出 400 错误,否则返回响应数据。 This is Flask code of the server:这是服务器的 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

And my front-end part of application should send a POST request with a data and get a response.我的应用程序的前端部分应该发送一个带有数据的 POST 请求并得到响应。 I am trying to use fetch but it gets a 400 error though I send a JSON object with a data object:我正在尝试使用fetch ,但它收到 400 错误,尽管我发送了 JSON object 和data object:

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() })
}

Also I tried to use XMLHttpRequest :我也尝试使用XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open("POST", 'http://' + appUrl, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(data);

But I can't find out how to disable CORS and get a response data.但我不知道如何禁用 CORS 并获取响应数据。

if you are having CORS issue, always check if the server accept your origin of request (other than pythonanywhere.com ) if not, you should allow it from your server.如果您遇到 CORS 问题,请始终检查服务器是否接受您的请求来源( pythonanywhere.com ),如果没有,您应该从您的服务器允许它。

you mentioned that you are using Flask as your backend, you might want to check out this library:你提到你使用 Flask 作为你的后端,你可能想看看这个库:

https://flask-cors.readthedocs.io/en/latest/ https://flask-cors.readthedocs.io/en/latest/

if you follow the docs from the link, you can allow, accept http request depends on the parameter you provided.如果您按照链接中的文档进行操作,则可以允许,接受 http 请求,具体取决于您提供的参数。

Happy Coding快乐编码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM