Steps to setup and test the different types of request with expressJS
Step 1: Create a simple project, use the following command.
npm init -y
Step 2: There are two dependencies that we have to add in our project, first is express and another one is body-parser. Install these by running the following command.
npm install express body-parser
Step 3: Now create a simple javascript file in our case lets say app.js, and use the following code, in this we have implemented the bodyParser to read the json data and we have set up the GET, POST, and DELETE request.
Javascript
const express = require( 'express' ); const app = express(); const bodyParser = require( 'body-parser' ); app.use(bodyParser.json()); // In-memory data store let posts = [ { id: 1, title: 'Hello World' }, { id: 2, title: 'Hello Node' }, { id: 3, title: 'Hello Express' }, // ... other posts ]; // GET request - Retrieve all posts app.get( '/posts' , (req, res) => { res.json(posts); }); // POST request - Create a new post app.post( '/posts' , (req, res) => { const newPost = { id: posts.length + 1, title: req.body.title }; posts.push(newPost); res.status(201).json(newPost); }); // PUT request - Update an existing post app.put( '/posts/:id' , (req, res) => { const post = posts.find( p => p.id === parseInt(req.params.id) ); if (!post) return res.status(404).send( 'Post not found.' ); post.title = req.body.title; res.json(post); }); // DELETE request - Delete a post app. delete ( '/posts/:id' , (req, res) => { posts = posts .filter(p => p.id !== parseInt(req.params.id)); res.status(204).send(); }); // Start the server const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server is running on port ${port}`); }); |
Step 4: Run the code using the following command.
node app.js
Output: After running the code, the server will run on the port : 300, and now we can use this link to test the API on the postman. http://localhost:3000/posts
GET Request : We can see in the image below that all the posts are displayed below.
How to send different types of requests (GET, POST, PUT, DELETE) in Postman.
In this article, we are going to learn how can we send different types of requests like GET, POST, PUT, and DELETE in the Postman. Postman is a popular API testing tool that is used to simplify the process of developing and testing APIs (Application Programming Interface). API acts as a bridge between two software applications which enables them to communicate and share data. Postman provides a simple Graphical User Interface for sending HTTP requests Like GET, POST, Put, Delete, and viewing their responses.
Table of Content
- What are the Requests in the Postman?
- How to send GET Request?
- How to send POST Request?
- How to send PUT Request ?
- How to send DELETE Request?
- Steps to setup and test the different types of request with ExpressJS
Contact Us