【问题标题】:How to add variable numbers of parameter in url using expressJS?如何使用expressJS在url中添加可变数量的参数?
【发布时间】:2020-04-10 14:58:23
【问题描述】:

我在 nodejs 项目中使用 express 来调用端点并在控制台中打印参数。网址可以是:

/printInfo?id=xxx&value=xxx 

or

/printInfo?id=xxx

or

/printInfo?value=xxx

我该怎么做?

【问题讨论】:

    标签: node.js express url console.log get-request


    【解决方案1】:

    假设您只想了解如何读取查询字符串,您只需读取 req.query 变量上的值。这是一个简单的设置:

    routes/index.js

    var express = require('express');
    var router = express.Router();
    
    router.get('/printInfo', (req, res, next) => {
      res.send({ id: req.query.id, value: req.query.value});
    });
    
    module.exports = router;
    

    app.js

    const express = require('express');
    const indexRouter = require('routes/index');
    
    const app = express();
    
    app.use('/', indexRouter);
    
    app.listen(3000, () => console.log(`Example app listening on port 3000!`));
    

    现在,当您向http://localhost:3000/printInfo?id=1&value=test 发出请求时,您应该会看到(我安装了JSON Formatter 扩展):

    {
      "id": "1",
      "value": "test"
    }
    

    显示在该页面。

    这是一个 gif,显示它在我的机器上的外观:

    【讨论】:

    • 我想在命令提示符中打印这些值并将它们传递给另一个函数。我的脚本文件中需要这些值。我是第一次使用快递。对不起,如果这是一个愚蠢的问题
    • @Araf 您可以使用 console.log() 打印值,就像任何其他 JS 值一样。要将它们传递给函数,只需将 req.query.paramName 传递给函数,就像任何其他值一样。也许发布一个具体的例子,我可以帮忙?
    • 谢谢。我现在明白了。这几乎就像普通的 app.get 函数。非常感谢
    • 哦,router.get() 令人困惑。抱歉,我忘记了大多数示例都不是从那个开始的,我已经在 Express 杂草中待了好几个星期,但我忘记了。
    【解决方案2】:

    您从 URL 获得的数据并不完全清楚,但req.query 包含 URL 中的任何查询参数,您可以迭代该对象以查看其中的内容:

     for (let prop of Object.keys(req.query)) {
         console.log(prop, req.query[prop]);
     }
    

    而且,这是一个模拟演示,可以在本地 sn-p 中运行,但您可以在 Express 中的 req.query 上使用相同类型的代码:

        // define simulated req.query (this is built automatically in Express)
        let req = {
            query: {id: 34506, value: "$400.99"}
        };
    
        // iterate arbitrary properties of req.query
        for (let prop of Object.keys(req.query)) {
            console.log(prop, req.query[prop]);
        }

    或者,如果您知道可能存在哪些查询参数并且您只想测试哪些查询参数存在,您可以这样做:

    if ("id" in req.query) {
        // id property is present
        console.log(req.query.id);
    }
    if ("value" in req.query) {
        // value property is present
        console.log(req.query.value);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      • 2018-08-23
      • 2016-06-16
      • 2023-03-08
      • 1970-01-01
      • 2014-04-09
      • 2017-09-11
      相关资源
      最近更新 更多