我在同一個檔案中有 2 個 GET 函式。
一個用于dogid,另一個用于dogname。
//Operations for api/dogs/{dogId} route
//get operation
router.get('/:dogId', async (req,res)=>{
try{
const dog = await Dogs.findById(req.params.dogId);
res.json(dog);
}catch(error){
res.json({message:error});
}
})
和
//Operations for api/dogs/{dogName} route
//get operation
router.get('/:dogName', async (req,res)=>{
try{
const dog = await Dogs.find({'name': { $in: req.params.dogName}})
res.json(dog);
}catch(error){
res.json({message:error});
}
})
當我嘗試 npm start 時,它沒有任何問題。
但是在郵遞員中,當我為 http://localhost:3000/api/dogs/Sasha 發送 GET 操作時
然后它顯示以下內容:
{
"message": {
"stringValue": "\"Sasha\"",
"valueType": "string",
"kind": "ObjectId",
"value": "Sasha",
"path": "_id",
"reason": {},
"name": "CastError",
"message": "Cast to ObjectId failed for value \"Sasha\" (type string) at path \"_id\" for model \"Doggies\""
}
}
使用 dogname 獲取資料的代碼已經存在。但是由于 dogid 路由的 get 函式是在 dogname 路由之前撰寫的,因此會顯示此錯誤。
uj5u.com熱心網友回復:
問題是 GET api/dogs/:dogId 正在處理請求,因為它是在 GET api/dogs/:dogname 之前撰寫的。
要解決此問題,請嘗試更改您的 api 設計或使用不同的 HTTP 請求方法。例如 :
POST api/dogs/:dogId
GET api/dogs/:dogName
or GET api/animals/dogs/:dogId
GET api/dogs/:dogName
但不要這樣做:
GET api/dogs/:dogId
GET api/dogs/:dogName
uj5u.com熱心網友回復:
正如@Mohammad Ismail 已經指出的那樣,您需要使用不同的 HTTP 方法來區分 2 條路由。
還有另一種方法是使用query代替param
You send the request like localhost:3000/api/dog?dogName=abc
Then in your code: req.query.dogNamewill get you the valueabc
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/465391.html
上一篇:在應用匹配過濾器之前從MongoDBAtlasSearch獲取唯一值串列
下一篇:從另一個集合中的資料提高搜索分數
