简体   繁体   English

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

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

I'm working on an assignment for my web services class and can't figure out how to handle a null URL parameter.我正在为我的 Web 服务类分配作业,但无法弄清楚如何处理空 URL 参数。 Here is my code:这是我的代码:

    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 + '.')})

This code works fine with all parameters filled.此代码在填充所有参数的情况下工作正常。 But how do I handle a null parameter if I don't want, for example, salsa and type in the url localhost:port/nachos/1/cheese/tomatoes/hotsauce但是,如果我不想要,如何处理 null 参数,例如,salsa 并输入 url localhost:port/nachos/1/cheese/tomatoes/hotsauce

If I'm reading correctly the question is:如果我没看错,问题是:

How do I handle a null parameter if I don't want, for example, salsa and type in the url localhost:port/nachos/1/cheese/tomatoes/hotsauce如果我不想要,如何处理null参数,例如, salsa并输入 url localhost:port/nachos/1/cheese/tomatoes/hotsauce

You won't get null it simply won't match the route.您不会得到null它只是与路线不匹配。

You can make params optional like:您可以将参数设为可选,例如:

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

or add routes to match, which could get out of hand.或者添加路由来匹配,这可能会失控。

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

You don't really do optional arguments in a route definition that looks like this:您实际上并没有在如下所示的路由定义中执行可选参数:

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

because in order for the route to match, every one of the parameters must be present and for req.params to contain the right option, they must all be in the correct order.因为为了使路由匹配,每个参数都必须存在,并且req.params包含正确的选项,它们都必须按正确的顺序排列。 If these are variations, some of which are entirely optional, then matching them the way you were is just not the proper URL design and matching a varying URL like that in Express will be a bit of a pain.如果这些是变体,其中一些完全是可选的,那么按照您的方式匹配它们就不是正确的 URL 设计,并且像 Express 中那样匹配不同的 URL 会有点痛苦。

The simplest way I can think of is to just put the optional ingredients in a query string as in:我能想到的最简单的方法是将可选成分放在查询字符串中,如下所示:

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

Then, you just match the route: /nachos/:x as the only required options for the URL and everything else can be optionally specified in the querystring and you can write your code so that it defaults to "no" if the option is not present.然后,您只需匹配路由: /nachos/:x作为 URL 的唯一必需选项,其他所有内容都可以选择在查询字符串中指定,您可以编写代码,如果选项不是,则默认为“no”展示。 So, an order without hotsauce could be either of these:因此,没有 hotsauce 的订单可能是以下任一情况:

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

An order without hotsauce or salsa could just be this:没有辣酱或莎莎酱的订单可能是这样的:

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

Then, your request handler would look like this:然后,您的请求处理程序将如下所示:

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}.`);
});

I should mention that if this request is actually specifying an order, then it should probably be a POST, not a GET and the options should be in the body of the POST and they would take the same form as the querystring, probably encoded just like application/x-www-form-urlencoded from form POSTs.我应该提到,如果这个请求实际上是在指定一个订单,那么它可能应该是一个 POST,而不是一个 GET,选项应该在 POST 的正文中,它们将采用与查询字符串相同的形式,可能编码就像application/x-www-form-urlencoded来自表单 POST。

Passing parameters this way request to the API user to send the parameters in the correct order.以这种方式传递参数要求 API 用户以正确的顺序发送参数。 To handle the case you want (an ingredient missing), you would need to create another route to handle it.要处理您想要的情况(缺少一种成分),您需要创建另一条路线来处理它。 But you can do this in another way, like passing the parameters as query strings or even sending them on the request body (for non-GET routers preferably).但是你可以用另一种方式来做到这一点,比如将参数作为查询字符串传递,甚至在请求主体上发送它们(最好是非 GET 路由器)。

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

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