Bad request AJAX post to Spring API

Asked by At

I'm sending JSON data to my Spring API but I always get a bad request. I have tried some things. At first, chanceReward was of type Map<String, Object>. Later I thought it should be a String but it still had a bad request. I researched and thought I needed consumes = "application/json" in the annotation but result is the same. Not sure anymore what to do. Below is the code for my API:

@RequestMapping(value = "/chance/{id}/saveChanceRewards", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody Map<String, Object> saveChanceRewards(@PathVariable("id") String id,
        @RequestBody String chanceRewards) {

    try {
        JSONArray jsonArray = new JSONArray(chanceRewards);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject JObject = jsonArray.getJSONObject(i);
            System.out.println(JObject.getString("name") + " " + JObject.getString("weight"));
        }
    } catch(JSONException e) {
        _log.error("Error parsing JSON");
    }

    Map<String, Object> map = new HashMap<String, Object>();
    // TODO

    return map;
}

Below is the ajax code (inside a .jsp):

    let arrayRewards = [];
    // get the data from dynamic list of text fields
    for (let i = 1; i <= chanceRewardCount; i++) {
        arrayRewards.push({
            name: $('#chanceRewardName' + i).val(),
            weight: $('#chanceRewardWeight' + i).val()
        });
    }

    let data = {'data': arrayRewards};
    let jsonData = JSON.stringify(data);

    $.ajax({
        type: 'post',
        dataType: "json",
        data: data,
        contentType: 'application/json',    
        url: "${home}/chance/${id}/saveChanceRewards",
        method: 'post',
        success: function(response) {
            console.log('response', response);  
        },
        error: function(err) {
            console.log('error', err);
        }
    });

I'm using Spring Framework 3.2.1.

3 Answers

1
karfai On Best Solutions

The 400 Bad Request error is an HTTP status code that means that the request you sent to the website server, often something simple like a request to load a web page, was somehow incorrect or corrupted and the server couldn't understand it.

That mean the server not able to understand the request from your ajax.

First, change @RequestBody String chanceRewards to @RequestBody ChanceRewards chanceRewards

And define ChanceRewards and ChanceReward class.

class ChanceReward {

    private String name;

    private String weight;

    // Getter Setter ...

}

class ChanceRewards {

    private List<ChanceReward> data;

    // Getter Setter ...

}

If still failed, try open inspect mode and click network tab to check the request send from ajax.

0
htn On

Replace double quotes in your url: "${home}/chance/${id}/saveChanceRewards", by backtick.

0
peekay On

There are quite a few things going on here, so let's work on them!

First, I see you've stringified the data into jsonData, but your actual ajax post has data: data instead. Easy fix, just swap in the right variable.

Second thing I notice is that you're wrapping the rewards array in an object (with data = {'data': arrayRewards}) but your Java code expects the array itself (JSONArray) right out of the request body. So this will also throw an exception. You don't have to wrap the array with an object if it's not needed.

Lastly, you mention that you always get a "bad request", but what exactly do you mean? An "HTTP 400" error? Some other HTTP error? It might be useful to give more info on the exact error(s) you see on the javascript side and on the Java server side.

All the other things like worrying about making a ChanceReward / ChanceRewards class, accepts/consumes/produces headers, etc., are superfluous at this point. They are boilerplate niceties and you don't need any of them for this to work correctly.