0
0
Expressframework~5 mins

Why understanding res matters in Express

Choose your learning style9 modes available
Introduction

The res object in Express helps you send responses back to the user. Understanding it lets you control what the user sees after they make a request.

When you want to send a message or data back to a user after they visit a webpage.
When you need to send a file or image as a response to a user.
When you want to redirect a user to another page.
When you want to set status codes like 404 for 'Not Found' or 500 for 'Server Error'.
When you want to send JSON data from your server to a web app.
Syntax
Express
res.status(code).send(body)
res.json(object)
res.redirect(url)
res.sendFile(path)

res.status(code) sets the HTTP status code for the response.

res.send() sends a string or buffer as the response body.

Examples
Sends a 200 OK status with a simple text message.
Express
res.status(200).send('Hello World!')
Sends a JSON response with an object.
Express
res.json({ message: 'Success' })
Redirects the user to the '/home' page.
Express
res.redirect('/home')
Sends a file like an image to the user.
Express
res.sendFile('/path/to/file.jpg')
Sample Program

This Express app shows how res sends different responses: a text message, JSON data, and a redirect.

Express
import express from 'express';
const app = express();

app.get('/', (req, res) => {
  res.status(200).send('Welcome to the homepage!');
});

app.get('/json', (req, res) => {
  res.json({ greeting: 'Hello, JSON!' });
});

app.get('/redirect', (req, res) => {
  res.redirect('/');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always set the correct status code to help browsers and tools understand the response.

Use res.json() when sending data to APIs for easier parsing.

Remember to end your response with res.send(), res.json(), or similar methods to avoid hanging requests.

Summary

The res object controls what the server sends back to the user.

It can send text, JSON, files, or redirects.

Understanding res helps you build clear and useful web responses.