Search code examples
jsonajaxspring-bootjacksonthymeleaf

Why instead of json-object answer I get a "404 not found" response?


Please help me. Why instead of json-object answer I get a "404 not found" response?

I am sending a following json-object to the server:

let dayEvent = { "dateEvent": "someEvent" };
$.ajax({
    url: "/day",
    type: 'post',
    data: JSON.stringify(dayEvent),
    contentType: 'application/json',
    dataType: 'json'
}).done(function (data) {
    console.log(data);
    $("#response").text("Success: " + data);
}).fail(function (e) {
$("#response").text("Error: " + e); });

Further this controller processes the json-object:

@RestController
public class TaskExistController {
    @RequestMapping(method=RequestMethod.POST, produces="application/json", value="/day")
    public String dayEvent(@RequestBody TaskDataModel day) {

        System.out.println(day.getDateEvent());
        ObjectMapper objectMapper = new ObjectMapper();
        String json = null;
        try {
            json = objectMapper.writeValueAsString(day.getDateEvent());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return json;
    }
}

TaskDataModel code:

public class TaskDataModel {
String dateEvent;

public void setDateEvent(String dateEvent) {
    this.dateEvent = dateEvent;
}

public String getDateEvent() {
    return dateEvent;
}

@Override
public String toString() {
    return "TaskDataModel [dateEvent=" + dateEvent + "]";
}}

Solution

  • My assumption is that your Spring server application is running on http://localhost:8080. Therefore, try:
    url: "http://localhost:8080/day"

    I also see that you use contentType application/json, and on serverside you declare: produces="application/json" but not consumes="application/json" However, this is not the reason of the 404, but something you could consider to add.

    It's also good to know that instantiating an ObjectMapper is relatively expensive. So it is better to declare one on class level, instead of each time your endpoint is being called.