'Send json with Ajax to RestController of Spring Boot (Content type 'application/json;charset=UTF-8' not supported error)
I have a problem to send JSON data to the method of RestController. I got this kind of error shown below.
error: "Unsupported Media Type"
message: "Content type 'application/json;charset=UTF-8' not supported"
Here is my a related method in js.
function postQuestion() {
url = contextPath + "post_question/" + productId;
question = $("#question").val();
jsonData = {questionContent: question};
$.ajax({
type: 'POST',
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader(csrfHeaderName, csrfValue);
},
data: JSON.stringify(jsonData),
contentType: 'application/json'
}).done(function(response) {
$("#modalDialog").on("hide.bs.modal", function(e) {
$("#question").val("");
});
.....
}).fail(function() {
.....
});
}
Here is my method defined in RestController.
@PostMapping(value="/post_question/{productId}")
public ResponseEntity<?> postQuestion(@RequestBody Question question,
@PathVariable(name = "productId") Integer productId,
HttpServletRequest request) throws ProductNotFoundException, IOException {
LOGGER.info("QuestionRestController | postQuestion is called");
LOGGER.info("QuestionRestController | postQuestion | question : " + question.getQuestionContent());
LOGGER.info("QuestionRestController | postQuestion | productId : " + productId);
Customer customerUser = authenticationControllerHelperUtil.getAuthenticatedCustomer(request);
LOGGER.info("QuestionRestController | postQuestion | customerUser : " + customerUser.getFullName());
if (customerUser == null) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
questionService.saveNewQuestion(question, customerUser, productId);
return new ResponseEntity<>(HttpStatus.OK);
}
Here is my Question Entity shown below.
@Entity
@Table(name = "questions")
@Getter
@Setter
public class Question implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "question")
private String questionContent;
}
Even if I defined dataType:'json' in js or consumes={"application/json;charset=UTF-8"} in the method of RestController , All these couldn't help me fix my issue.
How can I fix it?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
