Back-End Dev | GET & POST Method In Express JS
Express JS is a popular web application framework for Node.js. It provides a robust set of features for building web applications and APIs. In this article, we will explore how to handle HTTP GET and POST requests in Express JS.
Handling HTTP GET Request With Express JS
When a client makes a GET request to a server, it is typically to retrieve data from the server. In Express JS, we can handle GET requests using the app.get
method. Here’s an example:
const express = require('express');
const app = express();
app.get('/users', (req, res) => {
// Retrieve and return users data
res.send('Retrieving users data');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, when a GET request is made to the ‘/users’ endpoint, the server retrieves and returns users data. This is a simple example, but in real-world applications, you would typically retrieve data from a database or another external data source.
Handling HTTP POST Request With Express JS
When a client makes a POST request to a server, it is typically to submit data to the server. In Express JS, we can handle POST requests using the app.post
method. Here’s an example:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/users', (req, res) => {
// Process and save user data
const newUser = req.body;
// Save user to database
res.send(`User ${newUser.name} has been saved`);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, when a POST request is made to the ‘/users’ endpoint, the server processes and saves the user data. We use express.json()
middleware to parse the incoming request body as JSON. Then we access the request body using req.body
and save the user to the database.
Conclusion
Handling HTTP GET and POST requests is a fundamental part of building web applications and APIs. In this article, we have explored how to handle GET and POST requests with Express JS. By using the app.get
and app.post
methods, we can define the behavior of our server when specific HTTP requests are made. This allows us to build powerful and dynamic back-end systems for our web applications.