一起学习网 一起学习网


Node.js与Express构建简单RESTful API

开发 Node.js, Express, RESTful API, CRUD operations, web development 03-26

Building a Simple RESTful API with Node.js and Express

In this tutorial, we will walk through the steps to create a simple RESTful API using Node.js and Express. This API will allow users to perform basic CRUD (Create, Read, Update, Delete) operations on a list of items.

Prerequisites

Before we begin, ensure you have the following installed on your machine:

  • Node.js
  • npm (Node package manager)

Step 1: Set Up the Project

  1. Create a new directory for your project and navigate into it:

    mkdir simple-rest-api
    cd simple-rest-api
    
  2. Initialize a new Node.js project:

    npm init -y
    

    This command will create a package.json file with default settings.

  3. Install Express:

    Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

    npm install express
    

Step 2: Create the Server

  1. Create a new file named server.js:

    touch server.js
    
  2. Set up a basic Express server:

    Open server.js in your favorite code editor and add the following code:

    const express = require('express');
    const app = express();
    const PORT = process.env.PORT || 3000;
    
    app.use(express.json());
    
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}`);
    });
    

    This code sets up an Express server that listens on port 3000 (or a port specified in the environment variables).

Step 3: Define the API Endpoints

  1. Create a simple in-memory data store:

    For simplicity, we'll use an array to store our items.

    let items = [];
    
  2. Define the CRUD endpoints:

    Add the following code to server.js to handle CRUD operations:

    // Create a new item
    app.post('/items', (req, res) => {
      const item = req.body;
      items.push(item);
      res.status(201).send(item);
    });
    
    // Read all items
    app.get('/items', (req, res) => {
      res.status(200).send(items);
    });
    
    // Update an item
    app.put('/items/:id', (req, res) => {
      const id = parseInt(req.params.id, 10);
      const updatedItem = req.body;
      items = items.map((item, index) => (index === id ? updatedItem : item));
      res.status(200).send(updatedItem);
    });
    
    // Delete an item
    app.delete('/items/:id', (req, res) => {
      const id = parseInt(req.params.id, 10);
      items = items.filter((_, index) => index !== id);
      res.status(204).send();
    });
    
    • POST /items: Adds a new item to the list.
    • GET /items: Retrieves all items.
    • PUT /items/:id: Updates an item by its index.
    • DELETE /items/:id: Deletes an item by its index.

Step 4: Test the API

  1. Start the server:

    Run the following command in your terminal:

    node server.js
    

    You should see the message "Server is running on port 3000".

  2. Test the endpoints:

    You can use a tool like Postman or curl to test the API endpoints.

    • Create an item:

      curl -X POST -H "Content-Type: application/json" -d '{"name": "Item 1"}' http://localhost:3000/items
      
    • Get all items:

      curl http://localhost:3000/items
      
    • Update an item:

      curl -X PUT -H "Content-Type: application/json" -d '{"name": "Updated Item"}' http://localhost:3000/items/0
      
    • Delete an item:

      curl -X DELETE http://localhost:3000/items/0
      

Conclusion

Congratulations! You've successfully created a simple RESTful API using Node.js and Express. This basic setup can be expanded with more complex logic, error handling, and integration with a database for persistent storage.


编辑:一起学习网