Express.js: Send Responses

04/12/20191 Min Read — In JavaScript, Node.js

At some point, you have to send data from your back end (Node.js/Express.js) over the wire to your front end.

Express makes it easy for you.

Let's say you have a GET request to a resource on the backend.

app.get('/book/:id', async (req, res) => {
  // fetch the data from the database, for example from MongoDB
  try {
    const book = await Book.findbyId(req.user.id})
    // then send the data with a HTTP code
    res.status(200).send(book)
    } catch (error) {
    // or send the error
    res.status(404).send(error)
    }
})

Here, Express handles requests to the endpoint /books with a Book id path. That means that the client will send a GET request your server and ask for the info about a book with a specific ID.

On the server, you first query the data from your database. In the example above, we call the Mongo database asynchronously with the help of Moongose's findbyId().

When we have the data, we return it with a Response object. We send the HTTP status with a status code using res.status(code). Then res.send(body) transmits the actual data.

Pitfall: Status Code 204

Status code 204 means "No Content". Express is smart enough to swallow your response body and won't send it.

So this code

res.status(204).send('Success!')

will send the status code, but not the attached string.

Further Reading