简体   繁体   中英

How can I send a payload with GET request using jquery?

I'm able to send and receive the below GET request with a payload using cURL & Python Flask; but unable to do so using 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);
                }
        });   

My server side code is given below:

@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

I understand that GET is supposed to have only query string paramters. But if I have a requirement to design such an API, how can I perform such a request using jquery?

Note: I'm a beginner in web-development :)

You can send payload with GET request but not using the browser ie jQuery or axios or fetch.

In your example since it is only one paramter, you can send it as query string. But as Klaus said, your API design needs change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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