我正在尝试使用 fetch API 从我的代码中删除 JQuery,但在将数据发送到服务器时遇到问题:
这是我的功能:
url = '/authentication'
fetch(url, {
method: 'POST',
headers: {"Content-Type" : "application/json"},
body: {username: username}
});
和 Spring 端:
@PostMapping("/authentication", produces = "application/json")
@ResponseBody
public String authentication(HttpServletRequest request, @RequestParam(name = "username") String username){
...
}
但我收到以下错误:
Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'username' is not present]
使用 fetch 发送数据的正确方法是什么,我做错了什么?
我尝试放置 JSON.stringify
或使用 {"username":username}
但它不会改变任何内容。
感谢您的帮助
编辑 06/24 :我用 url = '/authentication?username='+username
解决了这个问题,但我遇到了一个很长的 jsonResponse
问题,其中有很多字符...(请求 header 太大
,仅在我的手机上)
最佳答案
@RequestParam 会解析 url 中的 var。
url = '/身份验证?用户名=abc'
如果你想与postbody打交道
public String authentication(HttpServletRequest request, @RequestBody YourRequest request)
你的请求.java
@Data
public class YourRequest {
private String username;
}
关于javascript - 所需的字符串参数不存在 : communicate with fetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56681872/