邮递员显示 404 而其余 api 实际上被调用

Postman shows 404 while the rest api is actually called

我有下面的 spring 启动 api,我正试图从 Postman 调用它:

@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(value = "/productList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<Product> listAllProducts() {
    // fetch products and send the list
    List<Product> products = somemethod();
    logger.info("No of products fetched : " + products.size());
    return products;
}

邮递员[=3​​0=]:GET --> http://localhost:5000/shop/productList

这是我在邮递员中的回复:

{
    "timestamp": "2021-07-21T13:05:48.431+00:00",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/shop/productList"
}

我可以看到日志正在打印正确的值。我不确定 return 响应中发生了什么。 最初 return 类型是 ResponseEntity,我将其更改为 List<Product>。之后就停止工作了。

返回列表需要您的控制器能够序列化输出。正如 ZIHAO LIU 所述,为此你需要在你的方法上使用 class 级别的 @RestController 注释或 @ResponseBody。

如果您不想添加这些注释,您也可以将您的列表包装在 ResponseEntity 中,如下所示:

@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(value = "/productList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Product>> listAllProducts() {
    // fetch products and send the list
    List<Product> products = somemethod();
    logger.info("No of products fetched : " + products.size());
    return ResponseEntity.ok().body(products);
}
 

在任何情况下,如果您不使用上述注释之一,您将需要 return ResponseEntity。