In Express.js, handling GET and POST requests involves defining routes and implementing route handlers to process incoming requests. Here's a basic example of handling GET and POST requests using Express:
-
Setup your Express app:
Install Express if you haven't already:
npm install expressCreate a file (e.g.,
app.js) and set up a basic Express app:const express = require('express'); const app = express(); const port = 3000; // Middleware to parse JSON in request bodies app.use(express.json()); // Serve static files (optional) app.use(express.static('public')); // Start the server app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); }); -
Handling GET requests:
Define a route for handling GET requests:
app.get('/', (req, res) => { res.send('Hello, this is a GET request!'); });In this example, when a user accesses the root URL (
/) with a GET request, the server responds with "Hello, this is a GET request!" -
Handling POST requests:
Define a route for handling POST requests:
app.post('/post-example', (req, res) => { const dataFromBody = req.body; // Access the data sent in the request body res.json({ message: 'This is a POST request!', data: dataFromBody }); });In this example, when a user sends a POST request to the
/post-exampleroute, the server responds with a JSON object containing a message and the data sent in the request body.Note: To test POST requests, you can use tools like
curl, Postman, or tools integrated into your development environment. -
Run your Express app:
node app.jsVisit
http://localhost:3000/in your browser for the GET request, and use a tool like Postman orcurlto send a POST request tohttp://localhost:3000/post-example.
Remember that this is a basic example, and in a real-world application, you might want to add more error handling, validation, and possibly use a router to organize your code better. Express provides a lot of flexibility and additional features for handling different types of requests and building robust APIs.