Reputation: 201
I have an web application and I'm trying to creat a simple POSt method that will have a value inside the body request:
@RequestMapping(value = "/cachettl", method = RequestMethod.POST)
@CrossOrigin(origins = "http://localhost:3000")
public @ResponseBody String updateTtl(@RequestBody long ttl) {
/////Code
}
My request which I call from some rest client is:
POST
http://localhost:8080/cachettl
Body:
{
"ttl": 5
}
In the response I get 403 error "THE TYPE OF THE RESPONSE BODY IS UNKNOWN
The server did not provide the mandatory "Content-type" header."
Why is that happening? I mention that other GET requests are working perfectly.
Thanks!
Edit: When I tried it with postman the error message I got is "Invalid CORS request".
Upvotes: 1
Views: 1659
Reputation: 13029
The error message is slightly misleading. Your server code is not being hit due an authentication error.
Since you say spring-security
is not in play then I suspect you're being bounced by a CORS violation maybe due to a request method restriction. The response body generated by this failure (if any at all) is automatic and will not be of the application/json
type hence the client failure. I suspect if you hit the endpoint with something that doesn't care for CORS such as curl
then it will work.
Does your browser REST client allow you to introspect the CORS preflight requests to see what it's asking for?
Upvotes: 0
Reputation: 665
Spring application just doesn't know how to parse your message's body. You should provide "header" for your POST request to tell Spring how to parse it.
"Content-type: application/json" in your case.
You can read more about http methods here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data
Updated:
Just in case of debug, remove useless annotations to test only POST mechanism. Also, change types of arg and return type. And try to use case-sensitive header.
@RequestMapping(value = "/cachettl", method = RequestMethod.POST)
public void updateTtl(@RequestBody String ttl) {
System.out.println("i'm working");
}
Upvotes: 1
Reputation: 17534
Since the error is about the response type, you should consider adding a produces
attribute, i.e :
@RequestMapping(value = "/cachettl", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
Since you are also consuming JSON, adding a consumes
attribute won't hurt either :
@RequestMapping(value = "/cachettl", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
Upvotes: 0