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 paramnamefrom thereq.queryobject.res.send(Hello ${name});- This line sends a response with the value of thenamequery param.app.listen(3000);- This line starts the Express.js server on port 3000.
Helpful links
More of Expressjs
- How do I find Express.js tutorials on YouTube?
- How do I download a zip file using Express.js?
- How can I use Zipkin to trace requests in Express.js?
- How do I use Zod with Express.js?
- How do I use Express.js to parse YAML files?
- How can I disable the X-Powered-By header in Express.js?
- How can I make an XHR request using Express.js?
- How do I implement CSRF protection in an Express.js application?
- How can I use the x-forwarded-for header in Express.js?
- How can I use Express.js to implement websockets in my application?
See more codes...