語境
嘗試GET為由查詢引數過濾的帖子發出 HTTP請求,authorId=x其中x可能是一個可能與任何帖子的authorId.
問題
json-server當沒有匹配的帖子時意外回傳 HTTP200而不是 HTTP404回應authorId(即回傳空陣列),如何將其更改為 return 404?同樣,這里的最佳 API 實踐是什么,是400像json-server已經做的那樣用 HTTP 回傳一個空陣列,還是用 HTTP 回傳空陣列404對用戶來說更清楚?
我看過jsonServer.rewriter&express中間件(例如,json-server檔案顯示它可以使用中間件進行配置server.use(middlewares),例如正在發送404一個空陣列,但json-server有內置的方法來處理這個問題還是有更好的方法?
歡迎所有建設性的反饋,謝謝。
代碼
db.json:
{
"posts": [
{
"authorId": 0,
"content": "Foo bar"
},
],
}
貝殼:
json-server --watch db.json
休息:
// Response status is expected HTTP 200.
GET http://localhost:5000/posts?authorId=0
這200將按預期回傳帶有 HTTP 的用戶:
[
{
"authorId": 0,
"content": "Foo bar",
}
]
// Response status is unexpected HTTP 200 but 404 was expected since response body contains an empty array. This is the problem.
GET http://localhost:5000/posts?authorId=does_not_exist
這將回傳一個帶有 HTTP 的空陣列200,這可能是意外的(不確定關于沒有匹配項的過濾集合的最佳實踐是什么,但這里的最佳實踐是什么以及如何將狀態更改為 HTTP 400:
[]
uj5u.com熱心網友回復:
正如@kindall 指出的那樣,回傳 404 可能是不明智的,但這也許是您正在嘲笑的 API 的現有行為。您可以回傳自定義輸出 - 從檔案:https : //github.com/typicode/json-server#custom-output-example
// In this example we simulate a server side error response
router.render = (req, res) => {
res.status(500).jsonp({
error: "error message here"
})
}
對于您的示例,它可能類似于(未經測驗的偽代碼):
// In this example we return 404 for no content
router.render = (req, res) => {
if (res.locals.data.posts.length < 1) {
res.status(404).jsonp({
error: "no posts"
});
} else {
res;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/378336.html
標籤:javascript json 表达 中间件 json服务器
