![]() |
VOOZH | about |
Node.js is a powerful JavaScript runtime for building server-side applications. It provides an efficient way to handle HTTP requests and responses using the built-in http module or frameworks like Express.js.
An HTTP request is sent by a client (browser or API) to a server, and the server processes it to return an HTTP response. The response contains a status code, headers, and body content.
Node.js has a built-in http module to create an HTTP server and handle requests.
Creates an HTTP server that listens for requests and responds with a message.
Defines different behaviors for GET and POST requests.
Express.js simplifies request and response handling with a minimal API.
Initializes an Express server and sets up a basic route.
Defines multiple routes to handle different HTTP methods.
Extracts query parameters from the request URL.
app.get('/search', (req, res) => {let query = req.query.q;res.send(`Search query: ${query}`);});
Retrieves dynamic values from the URL path.
app.get('/user/:id', (req, res) => {res.send(`User ID: ${req.params.id}`);});
Returns JSON-formatted responses for API requests.
app.get('/json', (req, res) => {res.json({ framework: 'Node.js', version: '16.0.0' });});
Middleware functions process requests before sending responses.
app.use((req, res, next) => {console.log(`Request received: ${req.method} ${req.url}`);next();});
Provides a centralized way to manage server errors.
app.use((err, req, res, next) => {console.error(err.stack);res.status(500).send('Something went wrong!');});