To get query string variables in Express.js on Node.js, we can use the req.query property.
For instance, we can write:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.json(req.query)
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
to return the req.query object as the response in the / route.
Then when we add ?foo=bar at the of the URL as the query string, we should see:
{
"foo": "bar"
}
returned as the response.
One reply on “How to Get Query String Variables in Express.js on Node.js?”
Hey, I’m reading your blog. It signifies something interesting and useful about node.js. Thank you! I definitely appreciate this site. Continue the good work!