简体   繁体   中英

Required String parameter is not present : communicate with fetch

I am trying to use fetch API to remove JQuery from my code and I have an issue sending the data to the server :

Here is my function :

url = '/authentication'
fetch(url, {
     method: 'POST',
     headers: {"Content-Type" : "application/json"},
     body: {username: username}
});

And Spring-side :

@PostMapping("/authentication", produces = "application/json")
@ResponseBody
public String authentication(HttpServletRequest request, @RequestParam(name = "username") String username){
...
}

but I got the following error :

Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'username' is not present]

What is the proper way to send data with fetch, and what am I doing wrong ? I tried to put JSON.stringify or with {"username":username} but it doesn't change anything.

Thanks for your help

EDIT 06/24 : I resolved it with url = '/authentication?username='+username , but I have issues with a long jsonResponse with a lots of characters... ( Request header is too large , only on my phone)

@RequestParam will parse the var in url.

url = '/authentication?username=abc'

if you want deal with postbody

public String authentication(HttpServletRequest request, @RequestBody YourRequest request)

YourRequest.java

@Data
public class YourRequest {


    private String username;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM