ExpressJS HTTP Methods (GET POST PUT DELETE)
When you interact with a website, you're constantly using different HTTP methods without realizing it. When you click a link, you're making a GET request. When you submit a form, you might be making a POST request. Express makes it easy to handle all these different types of requests.
What are HTTP Methods?
HTTP methods (also called HTTP verbs) indicate what action you want to perform on a resource. The most common ones are:
- GET: Retrieve data (like viewing a page)
- POST: Send data to create a new resource (like submitting a form)
- PUT: Update an existing resource completely
- DELETE: Remove a resource
GET Requests
GET is used to request data from a server. It should never modify any data. Think of it like looking at a menu in a restaurant – you're just reading, not changing anything.
app.get('/products', (req, res) => {
res.send('Here are all our products');
});
app.get('/products/1', (req, res) => {
res.send('Here is product with ID 1');
});POST Requests
POST is used to send data to create a new resource. For example, when you sign up for a website, you POST your information. In Express, POST data is usually sent in the request body.
app.post('/users', (req, res) => {
// Assume we get user data from req.body
res.send('User created successfully');
});PUT Requests
PUT is used to update an existing resource. For example, updating your profile information.
app.put('/users/1', (req, res) => {
// Update user with ID 1
res.send('User updated successfully');
});DELETE Requests
DELETE is used to remove a resource.
app.delete('/products/1', (req, res) => {
// Delete product with ID 1
res.send('Product deleted');
});Handling Different Methods on the Same Path
You can have different handlers for the same path but different HTTP methods. This is how RESTful APIs are built.
// GET all products
app.get('/products', (req, res) => {
res.send('Get all products');
});
// POST new product
app.post('/products', (req, res) => {
res.send('Create new product');
});
// PUT update product
app.put('/products/1', (req, res) => {
res.send('Update product');
});
// DELETE product
app.delete('/products/1', (req, res) => {
res.send('Delete product');
});Important Note About POST and PUT Data
To access data sent in POST or PUT requests, you need middleware that can parse the request body. Express provides built-in middleware for this:
app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing form dataThen you can access the data via
req.body.Two Minute Drill
- GET: Retrieve data (read)
- POST: Create new data (write)
- PUT: Update existing data (update)
- DELETE: Remove data (delete)
- Use different methods on the same path for different actions (REST API).
- Use
express.json()to parse request bodies.
Need more clarification?
Drop us an email at career@quipoinfotech.com
