💻 五分钟内构建 CRUD Express API!

2025-05-25

💻 五分钟内构建 CRUD Express API!

Express感兴趣?不确定如何开始使用MERN(MongoDB、Express.js、React.js、Node.js)?本教程将帮助您在五分钟内掌握完整的CRUD (创建、读取、更新、删除) REST (表述性状态转移) API 🐼

入门

本教程假设您已nodejs安装npm并配置了 MongoDB。如果没有,请留言,我会将我的后续文章 《安装和运行 Node.js》转发给您。

MVC 💎

我们的应用程序将遵循 MVC(模型、视图、控制器)设计模式

我将在稍后的文章中讨论设计模式,但现在,您需要知道的是 MVC 模式分为三个部分📝:

  • 模型- 模型表示一个承载数据的对象。它还可以包含逻辑,以便在数据发生变化时更新控制器。
  • 视图——视图代表模型包含的数据的可视化。
  • 控制器- 控制器作用于模型和视图。它控制流入模型对象的数据,并在数据发生变化时更新视图。它使视图和模型保持分离。

开始↙️

首先,让我们创建一个新的目录来开始工作:

  • 导航到您想要的目录
  • 运行mkdir my-express-app(创建项目文件夹)替代文本
  • 运行npm init -y(初始化你的节点项目)替代文本
  • 创建以下文件夹/文件(或复制并粘贴提供的命令!)
    • mkdir -p ./server/models; mkdir ./server/controllers; mkdir ./server/routes
    • 然后touch ./server/index.js; touch ./server/models/user.model.js; touch ./server/controllers/user.controller.js; touch ./server/routes/user.routes.js

现在你的项目应该看起来像这样! 👀

替代文本

创建服务器! 🌀

服务器需要三件东西才能运行:

  • 创建服务器应用程序
  • 使用路由中间件
  • 监听请求

让我们逐一分析一下

创建服务器应用程序

首先,我们需要安装一些依赖项。

在项目根目录下打开终端并运行以下命令: 这将安装两个包依赖项。什么是包依赖项?它们是一些包,是应用程序可以用来编写代码的 API。您的项目依赖于这些包才能运行(如果您使用了该包)。
npm install express mongoose
替代文本

Express是我们将用来创建服务器、路由和控制器的 API。
mongoose是一种功能类似于 ORM(对象关系映射器)的 API,我们将用它来创建数据库模型。

打开./server/index.js文件并粘贴以下代码



const express = require('express');

const app = express();

app.use(express.json());

app.get('/', (req, res) => {
    res.status(200).json({message: "Hello from my-express-app!"});
});

const PORT = 8080;

app.listen(PORT, () => {
    console.log(`Server listening at http://localhost:${PORT}`);
});


Enter fullscreen mode Exit fullscreen mode

逐行:



const express = require('express');


Enter fullscreen mode Exit fullscreen mode

导入 Express API,以便我们可以在我们的应用程序中使用它的功能。



const app = express();


Enter fullscreen mode Exit fullscreen mode

构建一个新的 Express 应用程序作为我们的服务器。



app.use(express.json());


Enter fullscreen mode Exit fullscreen mode

告诉 Express 应用程序使用 JSON 中间件(这样我们就可以看到带有 JSON 的请求主体)



app.get('/', (req, res) => {
    res.status(200).json({message: "Hello from my-express-app!"});
});


Enter fullscreen mode Exit fullscreen mode

创建GET路线并发送初始响应。

最后,package.json我们需要在我们的文件中添加一个脚本!
"server": "node server/index.js"
替代文本

跑步



npm run server


Enter fullscreen mode Exit fullscreen mode

在项目根目录的终端中,导航至http://localhost:8080/应该显示以下内容:
替代文本

控制器! 🔧

在创建CRUDAPI 时,我们需要创建至少四个控制器:

  • 创造
  • 更新
  • 删除继续将以下代码添加到./server/controllers/user.controller.js```c

exports.createOneRequest = (req, res) => {
res.status(201).json({message: "新资源已创建!"});
}

exports.readOneRequest = (req, res) => {
res.status(302).json({message: "找到资源!"});
}

exports.updateOneRequest = (req, res) => {
res.status(301).json({message: "资源已更新!"});
}

exports.deleteOneRequest = (req, res) => {
res.status(202).json({message: "资源已删除!"});
}


Each function is responsible for a corresponding HTTP request, and returns the following appropriate response status code, along with some JSON data to look at!
- 201 - Resource Created
- 302 - Resource Found
- 301 - Resource Moved Permanently
- 202 - Resource Accepted

These are the controllers that will handle our requests!

### **The Routes!** :bike:

Now we have our controllers, we need some routes for them to handle. We are going to use Express router to handle our CRUD routes!
In your `./server/routes/user.routes.js` add the following:
```c


const express = require('express');
const urlRoutes = express.Router();

const controller = require('../controllers/user.controller');

urlRoutes.post('/', controller.createOneRequest);
urlRoutes.get('/:id', controller.readOneRequest);
urlRoutes.put('/:id', controller.updateOneRequest);
urlRoutes.delete('/:id', controller.deleteOneRequest);

module.exports = urlRoutes;



Enter fullscreen mode Exit fullscreen mode

然后将以下内容添加到您的./server/index.js文件中:



const userRouter = require('./routes/user.routes');
...
app.use('/users', userRouter);
...


Enter fullscreen mode Exit fullscreen mode

这会将我们新创建的路由器挂载到/users子路由。这意味着我们指定的任何路径都必须在前面加上,/users以确保 URL 正确。

例如:http://localhost:8080/<SOME_OBJECT_ID>这是一个在我们当前项目结构下无法正常工作的 URL 示例。由于它前面添加了 ,所以
http://localhost:8080/users/<SOME_OBJECT_ID> 应该/users是一个正确的 URL !

现在,导航到任何 URL 都应该返回类似这样的响应!
替代文本

构建并集成模型! :octocat:

我们快到本教程的最后一部分了。如果你读到这里,恭喜你!你离一个很棒的 REST API 只差一步之遥了 😉

将以下代码添加到您的./server/models/user.model.js文件中:



const mongoose = require('mongoose');

const UserModel = mongoose.model('User', 
    mongoose.Schema(
        {
            name: {
                type: String
            },
        },
        {timestamps: true}
    )
);

module.exports = UserModel;


Enter fullscreen mode Exit fullscreen mode

这会在您的本地 MongoDB 实例中创建一个要使用的用户模式。

然后,回到./server/controllers/user.controller.js文件:

将 createOneRequest 请求的内容替换为:



exports.createOneRequest = async (req, res) => {
    // req.body is for POST requests. Think 'body of the postman'
    // destruct the name value from the request body
    const {name} = req.body;

    // check if database already contains this name
    const foundUser = await UserModel.find({name});

    // if no user is found, we can add this user to the database.
    if(!foundUser || foundUser.length == 0) {
        const user = new UserModel({name});
        const response = await user.save();
        res.status(201).json(response);
    } else {
        res.status(409).json({message: "User already exists!"});
    }
}


Enter fullscreen mode Exit fullscreen mode

该控制器现在可以处理三件事!

  • 根据提供的名称检查用户是否已经存在。
  • 如果不存在用户,则创建一个
  • 返回响应给客户端

对 执行相同操作readOneRequest



exports.readOneRequest = async (req, res) => {
    // Best request is GET, we can get the ID from the request 
    // parameters.
    const {id} = req.params;

    // attempt to retrieve user
    const foundUser = await UserModel.findOne({_id: id});

    // return 404 if no user found, return user otherwise.
    if(!foundUser || foundUser.length == 0) {
        res.status(404).json({message: "User not found!"});
    } else {
        res.status(302).json(foundUser);
    }
}


Enter fullscreen mode Exit fullscreen mode

对于putOneRequest




exports.updateOneRequest = async (req, res) => {
    const {id} = req.body;
    const foundUser = await UserModel.findOne({_id: id});
    if(foundUser || foundUser.length == 0) {
        const response = await foundUser.updateOne({_id: id});
        res.status(301).json(response);
    } else {
    res.status(404).json({message: `User not found...`});
    }
}


Enter fullscreen mode Exit fullscreen mode

最后,deleteOneRequest



exports.deleteOneRequest = async (req, res) => {
    const {id} = req.params;
    const foundUser = await UserModel.findOne({_id: id});
    if(foundUser || foundUser.length == 0) {
        const response = await foundUser.deleteOne({_id: id});
        res.status(202).json(response);
    } else {
        res.status(404).json({message: `User not found...`});
    }
}


Enter fullscreen mode Exit fullscreen mode

现在我们已经构建了 CRUD 操作,我们需要做的就是配置数据库,然后就可以开始了!

数据库连接! 📫

我们需要打开与 Mongo 数据库的连接,以便我们的应用程序可以与数据库通信!

为此,打开./server/index.js脚本并添加以下代码:



...
const mongoose = require('mongoose');

const db = mongoose.connect('mongodb://localhost:27017/db', {
    useCreateIndex: true,
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then((response) => {
    console.log('Connected to the database...');
    return response;
});
...


Enter fullscreen mode Exit fullscreen mode

快来npm run server体验一下你精心打造的全新完整 CRUD Rest API 吧!🙌

摘要👋

就是这样!一个功能齐全、功能齐全的 CRUD 方法 Restful API!我们讲解了如何构建 Express 应用、使用中间件和路由、路由控制器以及最终的数据库模型。真是一个很棒的教程!😫

欢迎在下方留言,任何反馈都欢迎!请给我一些你基于此开发的应用链接!

希望你喜欢这篇教程,也欢迎你关注我的其他社交媒体!这是我在这个网站上的第一篇帖子,请多多包涵😄

文章来源:https://dev.to/brandonkylebailey/build-a-crud-express-api-in- Five-minutes-42oc
PREV
什么是动态规划(Python 示例)背包问题
NEXT
如何管理程序员而不失去理智