Angular/Spring MVC:如何修复错误"Required request body is missing"

Angular/Spring MVC: how to fix the error "Required request body is missing"

我在从前端的数据库中删除产品时遇到问题 (angular)。 我有这个错误:

缺少必需的请求正文:public 布尔值 prodcust.controller.DeleteController.deleteProduct(java.lang.String,prodcust.model.Product)]

我在 Postman 中测试了删除 API,它工作正常,我只有在单击删除按钮时 Angular 才遇到这个问题。

控制器:

@RequestMapping(value = "/delete-product/{codeproduct}",method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public boolean deleteProduct(@PathVariable("codeproduct") String codeproduct, @RequestBody Product product) {
    product.setCodeproduct(codeproduct);
    return productDao.deleteProduct(product);
}

DAO:

public boolean deleteProduct(Product product) {
    boolean status=false;
    try {
        jdbcTemplate.update("delete from buys where codeproduct=?", product.getCodeproduct());
        status=true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return status;
}

Angular: service.ts

return this.http.delete(`${this.baseUrl}/delete-product/${codeproduct}`, { responseType: 'text' }); 

您的后端 API 需要 Product 类型的请求正文。但是 angular 调用 http.delete 没有传递它,这导致了错误。

相反,您可以使用 http.request 代替 json 作为正文:

return this.http.request('delete', `${this.baseUrl}/delete-product/${codeproduct}`, {body: prodObj}); 

@RequestBody Product product 尝试从 angular.

发送一些 json 对象或空 json {}

使用如下。

http.request('delete',. , `${this.baseUrl}/delete-product/${codeproduct}`, body: { } });