Brarord
Brarord

Reputation: 651

How to handle JSON data using POST method?

I have the following JSON in my request which is sended by JavaScript:

enter image description here

As you can see this is: String - String. Here is my JS code:

function saveSchemaInDatabase(schemaName, diagramJson) {
    var data = new FormData();
    data.append("schemaName", schemaName);
    data.append("diagramJson", diagramJson);

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
    };

    xhttp.open("POST", "/user/saveSchemaInDatabase", true);
    xhttp.send(JSON.stringify(Object.fromEntries(data)));
}

Here is my controller:

@PostMapping(path = { "/user/saveSchemaInDatabase" })
public String saveSchemaInDatabase(@RequestBody Map<String, String> map) {
    return "redirect:/user";
}

but i am getting error 415:

enter image description here

Can someone tell me how can i get that 2x params in my controller?

I tried also using DTO.
My DTO:

public class DTOTest {
    private String schemaName;
    private String diagramJson;

    public String getSchemaName() {
        return schemaName;
    }

    public void setSchemaName(String schemaName) {
        this.schemaName = schemaName;
    }

    public String getDiagramJson() {
        return diagramJson;
    }

    public void setDiagramJson(String diagramJson) {
        this.diagramJson = diagramJson;
    }
}

Controller:

@PostMapping(path = { "/user/saveSchemaInDatabase" })
public String saveSchemaInDatabase(@RequestBody DTOTest dtoTest) {
    return "redirect:/user";
}

the same error:
enter image description here

Upvotes: 0

Views: 64

Answers (3)

Brarord
Brarord

Reputation: 651

Solution:

function saveSchemaInDatabase(schemaName, diagramJson) {
    ...
    xhttp.open("POST", "/user/saveSchemaInDatabase", true);
    xhttp.setRequestHeader("Content-type", "application/json; charset=utf-8");
    xhttp.send(JSON.stringify(Object.fromEntries(data)));
}

Upvotes: 1

user404
user404

Reputation: 2028

I don't know if this will solve your problem or not as there are some things vague to me. You can try this way:

  1. Annotate your controller with @RestController
  2. In your ajax sending json data, add contentTyp as json i.e:
    contentType: "application/json; charset=utf-8",

And replace your tried code with this

@PostMapping(value =  "/user/saveSchemaInDatabase")
        public String saveSchemaInDatabase(@RequestBody DTOTest dtoTest) {
            return "redirect:/user";
        }

And please add your sample json data , not from browser console P.S: your diagramJson seems to be another json. you want that as string??

Upvotes: 1

Erty Seidohl
Erty Seidohl

Reputation: 4549

You likely need to send a Content-Type header with the value set to text/json in your JavaScript request.

Upvotes: 1

Related Questions