繁体   English   中英

如何使用 Express.js 处理空 URL 参数

[英]How to handle null URL parameters with Express.js

我正在为我的 Web 服务类分配作业,但无法弄清楚如何处理空 URL 参数。 这是我的代码:

    app.get('/nachos/:x/:cheese/:tomatoes/:salsa/:hotsauce', (req, res) => {
        var x = parseInt(req.params['x'])
        var cheese = (req.params['cheese'])
        var tomatoes = (req.params['tomatoes'])
        var salsa = (req.params['salsa'])
        var hotsauce = (req.params['hotsauce'])

        res.send('You ordered ' + x + ' nacho(s) with ' + cheese + ', ' + tomatoes + ', ' + salsa + ', ' 
        + hotsauce + '.')})

此代码在填充所有参数的情况下工作正常。 但是,如果我不想要,如何处理 null 参数,例如,salsa 并输入 url localhost:port/nachos/1/cheese/tomatoes/hotsauce

如果我没看错,问题是:

如果我不想要,如何处理null参数,例如, salsa并输入 url localhost:port/nachos/1/cheese/tomatoes/hotsauce

您不会得到null它只是与路线不匹配。

您可以将参数设为可选,例如:

app.get('/nachos/:x?/:cheese?/:tomatoes?/:salsa?/:hotsauce?', (req, res) => {

或者添加路由来匹配,这可能会失控。

app.get([
    //...
    '/nachos/:x/:cheese/:tomatoes',
    '/nachos/:x/:cheese/:tomatoes/:hotsauce',
    '/nachos/:x/:cheese/:tomatoes/:salsa/:hotsauce',
    //...
], (req, res) => {

您实际上并没有在如下所示的路由定义中执行可选参数:

/nachos/:x/:cheese/:tomatoes/:salsa/:hotsauce

因为为了使路由匹配,每个参数都必须存在,并且req.params包含正确的选项,它们都必须按正确的顺序排列。 如果这些是变体,其中一些完全是可选的,那么按照您的方式匹配它们就不是正确的 URL 设计,并且像 Express 中那样匹配不同的 URL 会有点痛苦。

我能想到的最简单的方法是将可选成分放在查询字符串中,如下所示:

 /nachos/2?cheese=yes&tomatoes=yes&salsa=yes&hotsauce=yes

然后,您只需匹配路由: /nachos/:x作为 URL 的唯一必需选项,其他所有内容都可以选择在查询字符串中指定,您可以编写代码,如果选项不是,则默认为“no”展示。 因此,没有 hotsauce 的订单可能是以下任一情况:

 /nachos/2?cheese=yes&tomatoes=yes&salsa=yes&hotsauce=no
 /nachos/2?cheese=yes&tomatoes=yes&salsa=yes

没有辣酱或莎莎酱的订单可能是这样的:

 /nachos/2?cheese=yes&tomatoes=yes

然后,您的请求处理程序将如下所示:

const orderOptions = ["cheese", "tomatoes", "salsa", "hotsauce"];

app.get('/nachos/:x', (req, res) => {
    console.log(req.query);

    let text = orderOptions.map(item => {
       return req.query[item] === "yes" ? item : null;
    }).filter(item => !!item).join(", ");

    res.send(`You ordered ${req.params.x} nacho(s) with ${text}.`);
});

我应该提到,如果这个请求实际上是在指定一个订单,那么它可能应该是一个 POST,而不是一个 GET,选项应该在 POST 的正文中,它们将采用与查询字符串相同的形式,可能编码就像application/x-www-form-urlencoded来自表单 POST。

以这种方式传递参数要求 API 用户以正确的顺序发送参数。 要处理您想要的情况(缺少一种成分),您需要创建另一条路线来处理它。 但是你可以用另一种方式来做到这一点,比如将参数作为查询字符串传递,甚至在请求主体上发送它们(最好是非 GET 路由器)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM