上下文
尝试对由查询参数authorId=x
过滤的帖子进行HTTPGET
请求,其中x
可以是可能不对应于任何帖子的authorId
的数字。
问题
当没有与authorId
匹配的帖子(即返回空数组(时,json-server
意外地返回HTTP200
而不是HTTP404
响应,如何将其更改为返回404
?同样,API在这里的最佳实践是什么?是像json-server
那样返回带有HTTP400
的空数组,还是使用HTTP404
返回空数组对用户来说更清楚?
我看过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
这将按预期向用户返回HTTP200
:
[
{
"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
这会返回一个带有HTTP200
的空数组,这可能是出乎意料的(不确定关于不匹配的过滤集合的最佳实践是什么,但这里的最佳实践会是什么&如何将状态更改为HTTP400
:
[]
正如@kindall所指出的,返回404可能是不明智的,但这可能是你嘲笑的API的现有行为。您可以从文档返回自定义输出:https://github.com/typicode/json-server#custom-输出示例
// 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.jsonp(res.locals.data);
}
}