Here's some ways of passing information from a client to a server:
-
In the URL:
- Route Params (ex.
https://localhost:3000/artists/madonna
) - Query String (ex.
https://localhost:3000/search?maxPrice=200
)
- Route Params (ex.
-
In the BODY of the http request:
- With some http request methods (for example, POST and PUT), it is possible to send additional data in what is called the "request body".
-
Example URL:
-
How to use route params in Express:
-
In your route's path: define the name for the params you expect
app.get('/artists/:artistname/', (req, res) => { });
-
Now we can get the info from
req.params
...app.get('/artists/:artistname/', (req, res) => { console.log(req.params); //req.params is an object const artist = req.params.artistName; });
-
-
Note: it is also possible to define multiple params. For example:
app.get('/artists/:artistname/albums/:albumName', (req, res) => { const artist = req.params.artistName; const album = req.params.albumName; });
-
Example URL:
-
How to use query string in Express
-
Read from the object
req.query
-
For example, 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; });
-
-
Note: we can also pass multiple options in the query string:
-
For example, 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 data from the body in Express
- We need to configure the package
body-parser
(no need to install since it comes with Express):
const bodyParser = require('body-parser'); // ... app.use(bodyParser.urlencoded({ extended: true }));
- Then we can read data from the object
req.body
app.post('/login', (req, res) => { console.log(req.body) if(req.body.email === 'bob@bob.com'){ //... } })
- We need to configure the package