Introduction
Response methods and status codes help your server tell the browser what happened with a request. They make communication clear and organized.
Jump into concepts and practice - no test required
Response methods and status codes help your server tell the browser what happened with a request. They make communication clear and organized.
res.status(code).send(body) res.status(code).json(object) res.send(body) res.json(object) res.redirect(url)
res is the response object in Node.js frameworks like Express.
status(code) sets the HTTP status code before sending the response.
res.status(200).send('OK')
res.status(404).send('Page not found')
res.json({ message: 'Hello' })res.redirect('/login')This simple Express server shows different response methods and status codes:
import express from 'express'; const app = express(); app.get('/', (req, res) => { res.status(200).send('Welcome to the homepage!'); }); app.get('/data', (req, res) => { res.json({ name: 'Alice', age: 30 }); }); app.get('/notfound', (req, res) => { res.status(404).send('Sorry, page not found'); }); app.get('/redirect', (req, res) => { res.redirect('/'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always set the status code before sending the response.
Use res.json() to send JSON data easily.
Common status codes: 200 (OK), 404 (Not Found), 500 (Server Error), 302 (Redirect).
Response methods send data and status codes tell the browser what happened.
Use res.status(code) to set status before sending.
Common methods: send(), json(), and redirect().
res.status(404) method do in a Node.js response?res.status()res.status(code) to set status, then call json() to send JSON data.status(200) and json(). Others misuse method order or names.app.get('/test', (req, res) => {
res.status(201).send('Created');
});res.status(201) sets status code 201 (Created), then send('Created') sends that text as the response body.app.get('/redirect', (req, res) => {
res.send('Redirecting...');
res.redirect('/new-url');
});res.send() is called, the response is sent and closed.res.redirect() after res.send() tries to send headers again, causing an error.res.status(400) to set the HTTP status to 400 (Bad Request).json() to send the JSON object with the error message.