In this tutorial, we aim to understand how to handle responses in Express, a flexible Node.js web application framework. You will learn how to structure your response, set response status, and send back appropriate data to the client.
By the end of this tutorial, you will be able to:
Before starting, it's recommended that you have a basic understanding of JavaScript and Node.js. Familiarity with Express would be beneficial but is not required.
Responses in Express are instances of the Response
object. This object has many methods to send HTTP responses. The most commonly used methods are res.send
, res.json
, and res.status
.
res.send
and res.json
Both res.send
and res.json
are used to send a response body. However, res.json
also converts non-object values into JSON.
app.get('/', function(req, res) {
res.send('Hello World')
})
In this example, the res.send
method sends a response of "Hello World" to the HTTP request.
res.status
The res.status
method is used to set the HTTP status code of the response.
app.get('/', function(req, res) {
res.status(404).send('Not found')
})
Here, we're sending a 404 status code with a message of "Not found".
Let's look at some examples to better understand response handling in Express.
app.get('/user', function(req, res) {
res.json({ name: 'John', age: 30 })
})
In this example, we are sending a JSON response containing user data.
app.get('/error', function(req, res) {
res.status(500).json({ error: 'Something went wrong' })
})
Here, we are sending a 500 (Internal Server Error) status code along with a JSON response that includes an error message.
In this tutorial, you've learned how to handle responses in Express, including how to set status codes and send various types of responses. To further expand your knowledge, you may want to investigate other response methods available in Express, such as res.render
for rendering view templates, or res.redirect
for redirecting to a different URL.
Here's a hint for the first exercise:
app.get('/bad-request', function(req, res) {
// Your code here
})
For more practice, try to create your own Express application and experiment with different types of responses. Good luck!