【发布时间】: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
我在 nodejs 项目中使用 express 来调用端点并在控制台中打印参数。网址可以是:
/printInfo?id=xxx&value=xxx
or
/printInfo?id=xxx
or
/printInfo?value=xxx
我该怎么做?
【问题讨论】:
标签: node.js express url console.log get-request
假设您只想了解如何读取查询字符串,您只需读取 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,显示它在我的机器上的外观:
【讨论】:
您从 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);
}
【讨论】: