This cheatsheet covers the following topics:
- URL: Route Params
- URL: Query String
- Request Body
-
Example URL:
-
How to use route params in Express:
- In the path, define a dynamic part with the syntax
/:something
- Inside the route, read from
req.params
- In the path, define a dynamic part with the syntax
-
Example 1:
app.get('/artists/:artistname/', (req, res) => { console.log(req.params); //req.params is an object const artist = req.params.artistName; });
-
Example 2 (multiple route params):
app.get('/artists/:artistname/albums/:albumName', (req, res) => { const artist = req.params.artistName; const album = req.params.albumName; });
-
Example URL:
-
How to read data from the query string:
req.query
-
Example 1:
-
If we receive a request
GET https://localhost:3000/search?maxPrice=120
app.get('/search', (req, res) => { console.log(req.query); // req.query is an object const price = req.query.maxPrice; });
-
-
Example 2 (multiple query strings):
-
If we receive a request
GET https://localhost:3000/search?maxPrice=120&location=berlin
app.get('/search', (req, res) => { const price = req.query.maxPrice; const location = req.query.location; });
-
-
Data is sent in the 'body' of the http request (also called 'payload').
-
How to read from the request body:
-
Step 1. Configure Express to be able to read incoming HTTP request that contain JSON data in the body.
app.use(express.json());
-
Step 2. Read data from the request body:
req.body
app.post('/login', (req, res) => { console.log(req.body) if(req.body.email === 'bob@bob.com'){ //... } })
-