Params in Express
Aug 24, 2020
In Express, route parameters are values derived
from portions of the URL that start with :. The the req.params property is where Express stores the values of the named sections in the URL.
const app = require('express')();
// `:userId` is a route parameter. Express will capture whatever
// string comes after `/user/` in the URL and store it in
// `req.params.userId`
app.get('/user/:userId', (req, res) => {
req.params; // { userId: '42' }
res.json(req.params);
});
const server = await app.listen(3000);
// Demo of making a request to the server
const axios = require('axios');
const res = await axios.get('http://localhost:3000/user/42');
res.data; // { userId: '42' }
Route parameters are also known as URL parameters.
Query String Parameters
Query string params are another commonly used type of parameter in Express.
The query string portion of
a URL is the part of the URL after the question mark ?.
By default, Express parses the query string and stores the parsed result on the request object as req.query:
const app = require('express')();
app.get('*', (req, res) => {
req.query; // { a: '1', b: '2' }
res.json(req.query);
});
const server = await app.listen(3000);
// Demo of making a request to the server
const axios = require('axios');
const res = await axios.get('http://localhost:3000/?a=1&b=2')
res.data; // { a: '1', b: '2' }
Built an Express app and want to deploy it?
We recommend Railway. It lets you deploy Node.js and Express apps without dealing with servers, Docker, CI/CD pipelines, or infrastructure. Click button, select GitHub repo, get URL. We've been using Railway for years to spin up apps quickly.
Deploy your Express app on Railway in minutes
We recommend Railway. It lets you deploy Node.js and Express apps without dealing with servers, Docker, CI/CD pipelines, or infrastructure. Click button, select GitHub repo, get URL. We've been using Railway for years to spin up apps quickly.
Deploy your Express app on Railway in minutes
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!