I'm using express in a nodejs project to call an endPoint and print the parameters after it in console. The url can be:
/printInfo?id=xxx&value=xxx
or
/printInfo?id=xxx
or
/printInfo?value=xxx
How can I do this?
I'm using express in a nodejs project to call an endPoint and print the parameters after it in console. The url can be:
/printInfo?id=xxx&value=xxx
or
/printInfo?id=xxx
or
/printInfo?value=xxx
How can I do this?
Assuming you just want to understand how to read the query string, you just read the values on the req.query
variable. Here is a simple setup:
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!`));
Now, when you make a request to http://localhost:3000/printInfo?id=1&value=test
you should see (I have the JSON Formatter extension installed):
{
"id": "1",
"value": "test"
}
Show up at that page.
Here is a gif showing how it looks on my machine:
It's not entirely clear to do with the data you get from the URL, but req.query
contains whatever query parameters are in the URL and you can just iterate that object to see what's there:
for (let prop of Object.keys(req.query)) {
console.log(prop, req.query[prop]);
}
And, here's a simulated demonstration which can run in a local snippet, but you can use the same type of code on req.query
in Express:
// 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]);
}
Or, if you know what possible query parameters may be there and you just want to test which ones are there, you can just do like this:
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);
}