如何使用jQuery发送带有GET请求的有效负载?

时间:2020-02-06 06:51:46

标签: python jquery flask

我可以使用cURL和Python Flask发送和接收以下带有有效负载的GET请求;但无法使用jquery来实现。

curl --location --request GET 'http://127.0.0.1:5000/image' \
--header 'Content-Type: application/json' \
--data-raw '{"task_id": "7f05f454-385a-415f-9bfb-225d77a16365"}'

jQuery:

    $.ajax({
                type: "GET",
                url: 'http://localhost:5000/image',
                data : JSON.stringify(body),
                contentType: 'application/json',
                success: function(response){
                    console.log("GET returned successfully");
                    console.log(response);
                    document.getElementById("divGetResponse").innerHTML = JSON.stringify(response);

                },
                error: function(error){
                console.log("GET failed");
                    console.log(error);
                }
        });   

我的服务器端代码如下:

@app.route('/image', methods=['GET'])
def getStatus():

   data = request.get_data()

   if not data:
        response = make_response(json.dumps('Invalid task_id'), 400)
        response.headers['Content-type'] = 'application/json'
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response

   if 'task_id' not in request.json or len(request.json['task_id']) == 0:
        response = make_response(json.dumps('Invalid task_id'), 400)
        response.headers['Content-type'] = 'application/json'
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response        

   task = conversionBgTask.AsyncResult(request.json['task_id'])

   if task.info is None:
      response = make_response(jsonify({'task_id' : '<task_id not found>'}), 204)
      response.headers['Content-type'] = 'application/json'
      response.headers['Access-Control-Allow-Origin'] = '*'
      return response

   response = make_response(jsonify(task.info), 200)
   response.headers['Content-type'] = 'application/json'
   response.headers['Access-Control-Allow-Origin'] = '*'
   return response

我了解GET应该只具有查询字符串参数。但是,如果我需要设计这样的API,该如何使用jquery执行这样的请求?

注意:我是网络开发的初学者:)

1 个答案:

答案 0 :(得分:1)

您可以使用GET请求发送有效内容,但不能使用浏览器(即jQuery或axios或提取)来

在您的示例中,由于它只是一个参数,因此可以将其作为查询字符串发送。但是正如克劳斯所说,您的API设计需要改变。