0

I simply want to send a value to my rest api in a fetch method but can't seem to get it to work. This is what I have currently:

React:

getFloorplans() {
        fetch('/api/ssid')
            .then(response => response.json())
            .then(message => {
                this.setState({
                    floorplan: message[0]
                })
            });

        fetch('/api/ssid', {
            method: "POST",

            //make sure to serialize your JSON body
            value: {ssid: this.state.SSID}
        })
            .then( (response => response.json()
                .then(message => {
                    console.log(message);
                })
        ))};

Spring boot rest api:

@RestController
public class FloorplanController {
    //Floorplan floorplan = new Floorplan();

    @RequestMapping("/api/ssid")
    public void someMethod(@RequestParam String value) {
        System.out.println(value);
    }
}

This is the error I'm currently getting: enter image description here

Dylan 75
  • 49
  • 1
  • 9
  • 1
    You should use `@PostMapping("/api/ssid")` if you are performing a POST request, the HTTP method is not specified at the moment. Second thing, I don't know a lot of React, but if you are sending your value as a JSON body you should use `@RequestBody` in your method. – burm87 Oct 29 '20 at 10:41
  • 1
    Also, I think you have to use `body` instead of `value`, as that is what `fetch` expects: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch – lewislbr Oct 29 '20 at 10:43
  • And how do I then get the data from the body in my controller? – Dylan 75 Oct 29 '20 at 10:47
  • 1
    I'm not familiar with Spring but you should have some request parameter to where extract the body @Dylan75 – lewislbr Oct 29 '20 at 11:15

2 Answers2

0

The exception is telling you that you are missing the request parameter. That's mean that value for @RequestParam String value in your controller is missing. The request should look like this http://yourhost/api/ssid?value=somevalue

Andrii Syd
  • 308
  • 5
  • 15
0

You should set headers, and params in body.

fetch('/api/ssid', {
     method: "POST",
     headers: {
          'Content-Type': 'application/json'
     },
     body: {ssid: this.state.SSID}
})
ecoplaneteer
  • 1,918
  • 1
  • 8
  • 29
  • This only confirms what data you're sending but I think the problem lies in my controller but I don't know how to extract the body data there – Dylan 75 Oct 29 '20 at 10:50
  • Refer this. https://stackoverflow.com/questions/32201441/how-do-i-retrieve-query-parameters-in-spring-boot – ecoplaneteer Oct 29 '20 at 12:38