简体   繁体   中英

400 bad request error in Ajax POST to spring RestController

I have ajax code as

/**
 * Ajax Logic for submitions
 * */
$.ajax({
    contentType : 'application/json; charset=utf-8',
    type: 'POST',
    url: '/domain/insert/',
    dataType : 'json',
    data : 'firstName:' + $("#first_name").val() /*+ "&lastName;=" + $("#lastName").val() + "&email;=" + $("#email").val()*/,
    success : function(callback){       
         console.log("Data inserted.........");
    },
    error : function(){
        console.log("Error.........");
    }
});

getting console out put as

POST http://localhost:8080/domain/insert/ 400 (Bad Request)
Z.cors.e.crossDomain.send @ common.min.js:3
J.extend.ajax @ common.min.js:3
t.length.t.steps.onStepChanged @ forms_wizard.min.js:34
J.event.dispatch @ common.min.js:2
m.handle @ common.min.js:2
J.event.trigger @ common.min.js:2
J.fn.extend.triggerHandler @ common.min.js:2
(anonymous function) @ wizard_steps.min.js:1
c @ common.min.js:2
d.fireWith @ common.min.js:2
(anonymous function) @ common.min.js:2
c @ common.min.js:2
d.fireWith @ common.min.js:2
a @ common.min.js:2
c @ common.min.js:2
d.fireWith @ common.min.js:2
d.fire @ common.min.js:2
J.extend.dequeue @ common.min.js:2
i.complete @ common.min.js:2
c @ common.min.js:2
d.fireWith @ common.min.js:2
I.l @ common.min.js:1
J.fx.tick @ common.min.js:3
forms_wizard.min.js:47 
Error.........

My insert method in RestController is

@RequestMapping(value = "/question/", headers="Accept=*/*", consumes="application/json", method = RequestMethod.POST)
    public ResponseEntity<Void> insert(@RequestBody User user) {
        System.out.println("Creating " + user.getFirstName()); 
        service.save(user);        
        return new ResponseEntity<Void>(HttpStatus.CREATED);
    }

OK, if I'm using Postman to POST data to controller it is succeeded but through above ajax code I'm getting 400 Error.....

your data property is the problem

you need to pass an json object in the data in order for this to work

data : {username: 'username'}

Wanted to write this as a comment, but can't yet...
What is your version of JQuery and if you post with Postman, what are your settings?
Would you also give the network request for the request and response?
Try to wrap data in brackets: {'firstName:' ... }

I've had a similar problem in the past (without spring though) and had to set the consumes to 'application/json; charset=utf-8' 'application/json; charset=utf-8' in the controller (although Intellij marks this as incorrect)

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