我正在嘗試構建郵遞員 GET 請求,以便使用資料庫中生成的唯一 ID 檢索我在 MongoDB 中的條目。
更準確地說,我有興趣撰寫一個 GET 請求來檢索例如下一個條目:
{
"id": "61a51cacdfb9ea1bd9395874",
"Name": "asdsd",
"Code": "asdca",
"Weight": 23,
"Price": 23,
"Color": "sfd",
"isDeleted": false
}
有沒有人知道如何在 GET 請求中包含該 id 以便從上面檢索產品?
謝謝!
編輯 :
@JF 感謝您提供的友好回復和資訊,但不幸的是,它仍然不起作用:(。
這些是我現在擁有的產品,我試圖獲得 id = 61a51cacdfb9ea1bd9395874 的產品

這是我得到的回應:

此外,這是我為 GET 請求實作的邏輯:
filename : product.service.ts
async getSingleProduct(productId: string) {
const product = await this.findProduct(productId);
return {
id: product.id,
Name: product.Name,
Code: product.Code,
Weight: product.Weight,
Price: product.Price,
Color: product.Price,
isDeleted: product.isDeleted };
}
private async findProduct(id: string): Promise<Product> {
let product;
try {
const product = await this.productModel.findById(id)
} catch (error) {
throw new NotFoundException('Product not found');
}
if (!product) {
throw new NotFoundException('Product not found');
}
return product;
}
filename : product.controller.ts
@Get(':id')
getProduct(@Param('id') prodId: string) {
return this.productsService.getSingleProduct(prodId)
}
編輯2:
@Controller('produse')
export class ProductsController {
constructor(private readonly productsService: ProductsService) {}
@Post()
async addProduct(
@Body('Name') prodName: string,
@Body('Code') prodCode: string,
@Body('Weight') prodWeight: number,
@Body('Price') prodPrice: number,
@Body('Color') prodColor: string,
@Body('isDeleted') prodIsDeleted: boolean,
) {
const generatedId = await this.productsService.createProduct(
prodName,
prodCode,
prodWeight,
prodPrice,
prodColor,
prodIsDeleted
);
return { id: generatedId };
uj5u.com熱心網友回復:
要實作 RESTful API,您的端點必須是這樣的:
| 動詞 | 小路 |
|---|---|
| 得到 | /resource |
| 得到 | /resource/:id |
| 郵政 | /resource |
| 放 | /resource/:id |
| 洗掉 | /resource/:id |
你想要的路徑是GET /resource/:id
在id使用到路由,因為是唯一的,確定的資源。
所以你的路徑可以是這樣的:
http://localhost:8080/v1/resource/61a51cacdfb9ea1bd9395874
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/371154.html
