【问题标题】:Create a route with "search url" as parameter using Express使用 Express 创建以“搜索 url”为参数的路由
【发布时间】:2018-08-04 07:26:03
【问题描述】:

使用 Express,我如何创建如下路线:

  • 当 URL /search?s=<SEARCH> 被调用时,回答 {status:200, message:"ok", data:<SEARCH>} 如果提供了
  • 如果未提供,则答案应为{status:500, error:true, message:"you have to provide a search"}

请务必将 HTTP 状态也设置为 500。

【问题讨论】:

  • 500 状态码是为内部服务器错误保留的。您确定要使用它吗?如果请求无效,您应该发送 4XX 错误(错误请求或类似请求)

标签: express


【解决方案1】:

此代码检查是否已添加查询参数s 并按要求回复。如果没有名为s 的查询参数,则req.query.s 将是undefinded。 (Docs) 在这种情况下,会发送一个 HTTP-500 应答。

app.get('/search',(req,res) => {
    const search = req.query.s;

    if (typeof search != 'undefined') {
        // Search string applied
        const response = {
            status:200, message:"ok", data: search
        };

        res.send(response);
    }
    else {
        const response = {
            status:500, error:true, message: "you have to provide a search"
        };


        res.status(500);
        res.send(response);
    }
});

此代码的优点是,正确的 Content-Type 标头由 express 自动设置。生成的对象也将采用 JSON 格式,因此任何客户端都可以直接使用它。

请注意,500 Internal Server Error 状态不应应用于此处描述的情况。 404 Not found 可能是更好的解决方案。

【讨论】:

    猜你喜欢
    • 2012-05-26
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    相关资源
    最近更新 更多