Introduction
In this project, you will learn how to develop a RESTful API using Node.js and Express.js. The project involves creating a simple user management system, where you can retrieve a list of users.
👀 Preview
curl http://localhost:8080/list
## Output:
## {"userlist":[{"id":"1","username":"zhangsan","password":"123456"},{"id":"2","username":"lilei","password":"456"},{"id":"3","username":"hanmeimei","password":"123"}]}
🎯 Tasks
In this project, you will learn:
- How to set up a Node.js project and install dependencies
- How to create a basic Express.js server
- How to implement a GET endpoint to retrieve a list of users from a JSON file
- How to test the API using cURL
🏆 Achievements
After completing this project, you will be able to:
- Understand the basics of RESTful API development
- Set up a Node.js project and install necessary dependencies
- Create a simple Express.js server
- Implement a GET endpoint to retrieve data from a JSON file
- Test the API using cURL
Set Up the Project
In this step, you will set up the project and install the necessary dependencies.
The initial code for this question has already been provided. Open the coding environment, and the directory structure is as follows:
├── index.js
├── users.json
├── package.json
├── package-lock.json
Next, download the dependencies using the npm install command in the terminal, wait for the dependencies to finish downloading and then start the project using the npm run dev command.
Implement the GET /list Endpoint
In this step, you will implement the GET /list endpoint to display the list of users.
- Open the
index.jsfile in the project directory. - Locate the TODO section in the file and add the following code to implement the GET /list endpoint:
//TODO
app.get("/list", function (req, res) {
fs.readFile(
path.resolve(__dirname, "./users.json"),
"utf8",
function (err, data) {
data = JSON.parse(data);
res.json(data);
}
);
});
This code reads the users.json file, parses the JSON data, and sends it as the response.
- Save the
index.jsfile.
Test the GET /list Endpoint
In this step, you will test the GET /list endpoint to ensure it is working correctly.
- Open a new terminal in the lab environment.
- Use the
curlcommand to send a GET request to the/listendpoint:
curl http://localhost:8080/list
You should see the following output, which is the JSON data from the users.json file:
{"userlist":[{"id":"1","username":"zhangsan","password":"123456"},{"id":"2","username":"lilei","password":"456"},{"id":"3","username":"hanmeimei","password":"123"}]}
If you see this output, the GET /list endpoint is working correctly.
Congratulations! You have completed the project and implemented the GET /list endpoint to display the list of users.
Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.



