When you’re building an API server, you need to pay attention to three kinds of data:
- Data in the path
- Data in the query string
- Data in the body
Data in the path
Data in the path is often called a param.
In Express, you can write create paths with params with :, like this:
app.get('/path/:param', handler)You can then get the param in the handler through req.params.
app.get('/path/:param', (req, res) => { const { param } = req.params})You’ve already seen a real params example when you used Github’s API to get a user’s repositories in our previous examples.
fetch('https://api.github.com/users/zellwk/repos')If we were to write this route handler in Express, it would look like this:
app.get('/users/:username/repos', (req, res) => { const { username } = req.params // Fetch repos associated with the username})Data in the query string
Data in the query string is also called query parameters.
You’ve seen this data when you change Github’s per_page query parameter to 100 in previous examples.
fetch('https://api.github.com/users/zellwk/repos?per_page=100')We can get query parameters in Express through the query object.
app.get('/users/:username/repos', (req, res) => { const { per_page } = req.query // Do something with per_page})Data in the body
To get data in the body, you need to use Express’s built-in middlewares.
Here, you will need two middlewares:
// Middlewaresapp.use(express.urlencoded({ extended: true }))app.use(express.json())Here’s what they’re used for.
express.urlencodedlets the server receivex-www-form-urlencodeddata.express.jsonlets the server receivejsondata
The extended option in express.urlencoded allows you to receive nested form data. This isn’t necessary but most developers have extended enabled because it’s a simple one-liner enhancement.
Now you can try sending in some form data and Express will be able to receive them.
<!-- In the client --><form method="post" action="/form"> <input type="text" name="message" /> <button type="submit">Send message</button></form>app.post('/form', (req, res) => { console.log(req.body)})You can also send in JSON data and Express will be able to receive them as well.
// In the clientzlFetch.post('https://localhost:3000/json', { body: { message: 'hello' },})app.post('/json', (req, res) => { console.log(req.body)})
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson