Status codes tell the browser or client what happened with a request. They help show if things worked or if there was a problem.
0
0
Status code conventions in Express
Introduction
When sending a response after a user requests a webpage or data.
When an error happens and you want to tell the client what went wrong.
When a user sends data to your server and you want to confirm it was saved.
When redirecting a user to a different page or URL.
When a requested resource is not found on the server.
Syntax
Express
res.status(code).send(body)
res is the response object in Express.
status(code) sets the HTTP status code for the response.
Examples
Sends a success message with status code 200.
Express
res.status(200).send('OK')
Tells the client the requested page was not found.
Express
res.status(404).send('Not Found')
Indicates a problem happened on the server.
Express
res.status(500).send('Server Error')
Confirms a new resource was created and sends its data.
Express
res.status(201).json({ id: 123 })
Sample Program
This Express app shows how to use status codes for different routes: success (200), not found (404), and created (201).
Express
import express from 'express'; const app = express(); app.get('/', (req, res) => { res.status(200).send('Welcome to the homepage!'); }); app.get('/notfound', (req, res) => { res.status(404).send('Page not found'); }); app.post('/create', (req, res) => { // pretend we create something here res.status(201).json({ message: 'Resource created' }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Always use the correct status code to help clients understand the response.
Common codes: 200 (OK), 201 (Created), 400 (Bad Request), 404 (Not Found), 500 (Server Error).
You can chain res.status() with other response methods like send() or json().
Summary
Status codes tell clients what happened with their request.
Use res.status(code) in Express to set the code.
Pick codes that match the situation for clear communication.