Node.js Tutorial 18: How to Update Data Using the PUT Method

Posted by

Updating Data with PUT Method – Node.js Tutorial 18

Updating Data with PUT Method – Node.js Tutorial 18

In this tutorial, we will learn how to update data using the PUT method in Node.js. PUT is one of the HTTP methods used for updating existing resources.

Creating a Node.js Server

First, let’s create a Node.js server using the http module. We will listen on a specific port, for example, port 3000.


const http = require('http');

const server = http.createServer((req, res) => {
// handle PUT request
});

server.listen(3000, () => {
console.log('Server is running on port 3000');
});

Handling PUT Request

To handle a PUT request, we need to check the request method and URL. We can use the req.method and req.url properties to do so.


const server = http.createServer((req, res) => {
if (req.method === 'PUT') {
if (req.url === '/update') {
// handle data update
}
}
});

Updating Data

Once we have identified the PUT request to update data, we can parse the incoming data and update the resource. We can use a database or a file system to store the updated data.


const server = http.createServer((req, res) => {
if (req.method === 'PUT') {
if (req.url === '/update') {
let body = '';

req.on('data', (chunk) => {
body += chunk;
});

req.on('end', () => {
// parse and update data
});
}
}
});

Conclusion

Now you have learned how to update data using the PUT method in Node.js. This is useful for building RESTful APIs and handling data modification in your applications.

Stay tuned for more tutorials on Node.js and web development!

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@matthewpool6508
10 months ago

Thank you, very helpful.

@codebreakthrough
10 months ago

⭐Check out UltraEdit – https://calcur.tech/Ultraedit
Node.js YouTube Playlist – https://calcur.tech/nodejs