Angle Tom
Angle Tom

Reputation: 1130

How to send a POST request to spring mvc application with Jquery

I created a controller like this.

@Controller
public class LoginController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    @ResponseBody
    public String hello() {
        return "hello world";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public User login(@RequestBody final User user) {
        return user;
    }

}

When I send a request with bash:

 curl -H "Content-Type: application/json" -d '{"username":"xyz"}' http://localhost:8080/mvc/login.do {"id":null,"name":null,"password":null}%

It works well.

But I got a error POST http://localhost:8080/mvc/login.do 415 (Unsupported Media Type), when I sent a request like this.

$.ajax({  method: "POST",
        data: JSON.stringify("{
            'id': 'test,
            'name': 'test1'
        }"),
        url:"login.do",
        timeout: 60000,
        success: sign_submited,
        error: ajaxError
    });

Upvotes: 1

Views: 883

Answers (1)

Gan
Gan

Reputation: 634

try to set content type in your ajax request as-- contentType:"application/json; charset=utf-8",

Upvotes: 3

Related Questions