deadlock
deadlock

Reputation: 182

Ajax request returns bad request error code

I am getting a bad request response to my request. I have checked with an online JSON validator my dictionary data to be correct, and everything seems fine.

My code is the following:

// Parse datetime to timestamp and include data in a dict
        let data_dict = {
            "stop_date": Date.parse(sup_limit.value),
            "start_date": Date.parse(inf_limit.value)
        }
        // Send the Ajax request
        let request = $.ajax({
            url: url,
            type: 'POST',
            data: data_dict,
            contentType: 'application/json;charset=UTF-8',
        });

Backend receive endpoint:

@dashboard_bp.route('/download_last_test_influx<mode>', methods=['GET', 'POST'])
@login_required
def download_last_test_influx(mode: str):
    # Check if request comes from a custom or test event
    if mode == 'custom':
        start_date = int(request.json.get('start_date'))
        stop_date = int(request.json.get('stop_date'))
        # Check if time range is valid, if not return server internal error
        if stop_date - start_date <= 0:
            return jsonify({'message': 'Time range must be grater than 0'}), 500
    # Create response header
    response = make_response(send_file(spock_comm_mgr
                                       .test_backup_influx_manager
                                       .get_last_test_influx_record(start_date=start_date, stop_date=stop_date)))
    response.headers['Content-Type'] = 'application/gzip'
    response.headers['Content-Encoding'] = 'gzip'
    return response

Request header:

POST /download_last_test_influxcustom HTTP/1.1
Host: 0.0.0.0:5000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json;charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 48
Origin: http://0.0.0.0:5000
Connection: keep-alive
Referer: http://0.0.0.0:5000/influx_management
Cookie: *********************

Request payload:

stop_date=1623758400000&start_date=1623708000000

Response message:

Bad Request

The browser (or proxy) sent a request that this server could not understand.

Upvotes: 0

Views: 363

Answers (1)

derpirscher
derpirscher

Reputation: 17382

You are telling your server, you are sending JSON data, but the request body is not a JSON string but a url-encoded string (because that's the default behaviour of $.ajax() when you pass an object as data).

Use JSON.stringify, to pass a correct JSON body

let request = $.ajax({
      url: url,
      type: 'POST',
      data: JSON.stringify(data_dict),
      contentType: 'application/json;charset=UTF-8',
    });

Upvotes: 1

Related Questions