Express.js Masterclass
The Professional Backend Framework01.Home02.Introduction03.Express vs Native Node04.Express Generator05.Request Object (req)06.Response Object (res)07.Advanced Routing08.URL Params & Query09.Body Parsing10.Template Engines (EJS)11.Serving Static Files12.Middleware Architecture13.Must-Have Middleware14.File Uploads (Multer)15.Custom Error Handling16.Cookies & Sessions17.User Auth (Passport)18.Database Integration19.Data Validation20.Socket.io in Express21.Security & Helmet
The Response Object (res)
The res object represents the HTTP response that an Express app sends when it gets an HTTP request.
Commonly Used Methods
| Method | Purpose | Example |
|---|---|---|
res.send() | Send a response of various types | res.send('Done') |
res.json() | Send a JSON response (Best for APIs) | res.json({ id: 1 }) |
res.status() | Set the HTTP status code | res.status(404) |
res.render() | Render a view template | res.render('index') |
res.redirect() | Redirect to a different URL | res.redirect('/login') |
res.sendFile() | Send a file as an octet stream | res.sendFile(path) |
Chaining Methods
You can chain methods together to set a status and send data in one line.
app.get('/api/users', (req, res) => {
res.status(201).json({ message: 'User created' });
});Redirections
Use res.redirect() to move users between pages, such as after a successful form submission.
app.get('/old-page', (req, res) => {
res.redirect(301, '/new-page'); // Permanent redirect
});Best Practice: Always use
res.json() when building APIs, as it automatically sets the Content-Type to application/json.