【发布时间】:2021-01-03 20:02:42
【问题描述】:
我正在使用 spring boot 开发简单的 rest api。我通过POST 方法创建用户。并通过DELETE 删除。但是当我使用 DELETE 和 json 服务器返回 Bad Request。
创建用户:
ubuntu@ubuntu-pc:~$ curl -X POST -H "Content-type: application/json" -d '{"name": "developer", "email": "dev@mail.com"}' http://localhost:8080/add-user
"OK"
获取用户:
ubuntu@ubuntu-pc:~$ curl http://localhost:8080
[{"id":"ff80818176c9b9720176c9bdfd0c0002","name":"developer","email":"dev@mail.com"}]
使用 json 删除用户:
ubuntu@ubuntu-pc:~$ curl -X DELETE -H "Content-type: application/json" -d '{"id": "ff80818176c9b9720176c9bdfd0c0002"}' http://localhost:8080/del-id
{"timestamp":"2021-01-03T19:47:15.433+00:00","status":400,"error":"Bad Request","message":"","path":"/del-id"}
使用 html 查询删除用户:
ubuntu@ubuntu-pc:~$ curl -X DELETE http://localhost:8080/del-id?id=ff80818176c9b9720176c9bdfd0c0002
"OK"
ubuntu@ubuntu-pc:~$ curl http://localhost:8080
[]
UserRepository.java
public interface UserRepository extends CrudRepository<UserRecord, String> {
}
用户服务.java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<UserRecord> getAllUsers() {
List<UserRecord> userRecords = new ArrayList<>();
userRepository.findAll().forEach(userRecords::add);
return userRecords;
}
public void addUser(UserRecord user) {
userRepository.save(user);
}
public void deleteUser(String id) {
userRepository.deleteById(id);
}
}
UserController.java
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/")
public List<UserRecord> getAllUser() {
return userService.getAllUsers();
}
@RequestMapping(value="/add-user", method=RequestMethod.POST)
public HttpStatus addUser(@RequestBody UserRecord userRecord) {
userService.addUser(userRecord);
return HttpStatus.OK;
}
@RequestMapping(value="/del-id", method=RequestMethod.DELETE)
public HttpStatus deleteUser(@RequestParam("id") String id) {
userService.deleteUser(id);
return HttpStatus.OK;
}
}
jvm 日志:
2021-01-03 22:47:15.429 WARN 30785 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'id' is not present]
我错了什么?
【问题讨论】:
-
如您所见,
DELETE端点在请求中只需要一个参数 (id) - 而不是 JSON 对象。所以,这个http://localhost:8080/del-id?id=ff80818176c9b9720176c9bdfd0c0002是正确的请求——如果你将它添加到 JSON 中的正文中,那么你会得到一个错误的请求(因为参数不在它应该在的位置)
标签: java json spring-boot http