首页 > 解决方案 > Java“错误”:“未找到”,“消息”:“没有可用消息”,

问题描述

我使用一个小型 Spring 应用程序,其中数据库中的值很少,我想使用可变调用检索它们。

API在这里,

@RestController
@RequestMapping("/api/v1/products")
public class ProductAPI {

    private ProductService service;

    @Autowired
    public void setService(ProductService service) {
        this.service = service;
    }


@GetMapping("/stock/")
public ResponseEntity<Product> findById(@RequestParam("productId") String productId) {

    Product product = service.findById(productId).get();
    return ResponseEntity.of(Optional.of(product));
}

...........
}

服务电话,

@Service
public class ProductService {


 private ProductRepository repository;

    @Autowired
    public void setProductRepository(ProductRepository productRepository) {
        this.repository = productRepository;
    }

    public Optional<Product> findById(String id) {

       return repository.findById(id);
    }
}

存储库类,

@Repository
 public interface ProductRepository extends CrudRepository<Product, String>{


 }

当我使用 cURL 拨打电话时,我收到消息,

   $ curl -X GET http://localhost:8080/api/v1/products/stock?productId=Product%20ID | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   142    0   142    0     0    845      0 --:--:-- --:--:-- --:--:--   850
{
  "timestamp": "2019-02-25T12:19:31.797+0000",
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "path": "/api/v1/products/stock"
}

我已正确插入数据库中的条目。这里有什么问题?

标签: javaspring-bootcurl

解决方案


因为你的映射中有额外的/

@GetMapping("/stock/")

所以如果你想要这样的请求

curl -X GET http://localhost:8080/api/v1/products/stock/?productId=Product%20ID

你需要像这样的映射:

@GetMapping("/stock")

在您当前的版本中,正确的 curl 看起来像:

http://localhost:8080/api/v1/products/stock/?productId=Product%20ID

推荐阅读