expressjsHow do I use query params with Express.js?
Query params are a way to pass data from a client to a server. With Express.js, you can access query params using the req.query
object. Here is an example of how to use query params with Express.js:
// server.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
const name = req.query.name;
res.send(`Hello ${name}`);
});
app.listen(3000);
If we make a request to http://localhost:3000/?name=John
, the output would be Hello John
.
Code explanation
const express = require('express');
- This line imports the Express.js library.const app = express();
- This line creates an Express.js app.app.get('/', (req, res) => {
- This line creates a GET route for the root path.const name = req.query.name;
- This line accesses the query paramname
from thereq.query
object.res.send(
Hello ${name});
- This line sends a response with the value of thename
query param.app.listen(3000);
- This line starts the Express.js server on port 3000.
Helpful links
More of Expressjs
- How do I set the time zone in Express.js?
- How can I use Express.js with TypeScript?
- How do I use Zod with Express.js?
- How can I use express-zip js to zip and download files?
- How do I find Express.js tutorials on YouTube?
- How can I use Express.js to generate a zip response?
- How can I use Express.js and Vite together for software development?
- How can I use the x-forwarded-for header in Express.js?
- How do I use Express.js to handle x-www-form-urlencoded data?
- How can I use Express.js and Winston together to create a logging system?
See more codes...