0
0
Node.jsframework~30 mins

HTTP methods and CRUD mapping in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
HTTP Methods and CRUD Mapping in Node.js
📖 Scenario: You are building a simple Node.js server to handle user data. You want to connect HTTP methods to CRUD operations so your server can create, read, update, and delete users.
🎯 Goal: Build a basic Node.js server using the http module that maps HTTP methods GET, POST, PUT, and DELETE to CRUD operations on a simple in-memory user list.
📋 What You'll Learn
Create an array called users with three user names: 'Alice', 'Bob', and 'Charlie'
Create a variable called port and set it to 3000
Use http.createServer to create a server that listens for HTTP requests
Inside the server callback, use req.method to check the HTTP method and handle GET, POST, PUT, and DELETE accordingly
💡 Why This Matters
🌍 Real World
Web servers use HTTP methods to perform CRUD operations on data. Understanding this mapping helps build APIs that clients like browsers or apps can use to manage data.
💼 Career
Backend developers often create RESTful APIs that map HTTP methods to CRUD actions. This knowledge is essential for building web services and working with frameworks like Express.js or Fastify.
Progress0 / 4 steps
1
Create the initial user data array
Create an array called users with these exact strings: 'Alice', 'Bob', and 'Charlie'.
Node.js
Need a hint?

Use const users = ['Alice', 'Bob', 'Charlie']; to create the array.

2
Set the server port
Create a variable called port and set it to the number 3000.
Node.js
Need a hint?

Use const port = 3000; to set the port number.

3
Create the HTTP server with method checks
Use http.createServer to create a server. Inside the callback, use req.method to check for 'GET', 'POST', 'PUT', and 'DELETE' methods. For now, just write empty blocks for each method inside the callback function.
Node.js
Need a hint?

Use http.createServer((req, res) => { ... }) and inside check req.method with if and else if.

4
Complete the server to respond with user data and start listening
Inside the 'GET' block, respond with the JSON string of users. Inside the 'POST', 'PUT', and 'DELETE' blocks, respond with a simple text message like 'Create user', 'Update user', and 'Delete user' respectively. Finally, call server.listen(port) to start the server.
Node.js
Need a hint?

Use res.setHeader and res.end to send responses. Use server.listen(port) to start the server.