cd express-rest-api
npm init -y
npm install express body-parser mongoose

在上面的命令中,我們首先創(chuàng)建了一個新的項目文件夾,然后安裝了Express.js、body-parser(用于解析請求體)和mongoose(用于MongoDB交互)。

創(chuàng)建基本的Express服務器

首先,我們要建立一個基礎的Express服務器。創(chuàng)建一個server.js文件,并在其中添加以下代碼:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const PORT = 3000;

// 中間件
app.use(bodyParser.json()); // 解析JSON格式的請求體

// 路由
app.get('/', (req, res) => {
res.send('Hello World! This is a simple RESTful API.');
});

// 啟動服務器
app.listen(PORT, () => {
console.log(Server is running on http://localhost:${PORT}); });

運行node server.js啟動服務器,然后在瀏覽器中訪問http://localhost:3000,你應該能看到“Hello World! This is a simple RESTful API.”的消息。

CRUD操作的實現(xiàn)

我們將使用一個簡單的模型來演示CRUD操作。在這個例子中,我們將構(gòu)建一個“用戶”模型,包含名稱和郵箱屬性。使用Mongoose連接到MongoDB數(shù)據(jù)庫,并實現(xiàn)CRUD操作。

首先,安裝MongoDB并確保你的數(shù)據(jù)庫正在運行。然后,在server.js文件中添加Mongoose連接代碼:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/expressRestApi', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('MongoDB connected'))
.catch(err => console.error('MongoDB connection error:', err));

創(chuàng)建用戶模型

接下來,我們需要定義用戶的Mongoose模型。創(chuàng)建一個名為User.js的文件,并添加以下代碼:

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
});

const User = mongoose.model('User', UserSchema);

module.exports = User;

實現(xiàn)CRUD接口

現(xiàn)在,回到server.js文件,添加CRUD操作的路由:

const User = require('./User');

// 創(chuàng)建用戶(Create)
app.post('/users', async (req, res) => {
const { name, email } = req.body;
const user = new User({ name, email });
try {
await user.save();
res.status(201).json(user);
} catch (err) {
res.status(400).json({ message: err.message });
}
});

// 獲取所有用戶(Read)
app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
res.status(500).json({ message: err.message });
}
});

// 更新用戶(Update)
app.patch('/users/:id', async (req, res) => {
const { id } = req.params;
const { name, email } = req.body;
try {
const user = await User.findByIdAndUpdate(id, { name, email }, { new: true });
res.json(user);
} catch (err) {
res.status(400).json({ message: err.message });
}
});

// 刪除用戶(Delete)
app.delete('/users/:id', async (req, res) => {
const { id } = req.params;
try {
await User.findByIdAndDelete(id);
res.json({ message: 'User deleted' });
} catch (err) {
res.status(500).json({ message: err.message });
}
});

測試API

現(xiàn)在,我們已經(jīng)實現(xiàn)了一個簡單的CRUD API,你可以使用Postman或cURL進行測試。

  1. 創(chuàng)建用戶(POST請求到http://localhost:3000/users):
{
"name": "John Doe",
"email": "john@example.com"
}
  1. 獲取所有用戶(GET請求到http://localhost:3000/users)。
  2. 更新用戶(PATCH請求到http://localhost:3000/users/{userId}):
{
"name": "Jane Doe",
"email": "jane@example.com"
}
  1. 刪除用戶(DELETE請求到http://localhost:3000/users/{userId})。

完整代碼

在這個簡單的教程中,我們使用Express.js和Mongoose成功創(chuàng)建了一個RESTful API,處理了CRUD操作。以下是完整的server.js文件代碼:

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const User = require('./User');

const app = express();
const PORT = 3000;

mongoose.connect('mongodb://localhost:27017/expressRestApi', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('MongoDB connected'))
.catch(err => console.error('MongoDB connection error:', err));

app.use(bodyParser.json());

app.get('/', (req, res) => {
res.send('Hello World! This is a simple RESTful API.');
});

// Create User
app.post('/users', async (req, res) => {
const { name, email } = req.body;
const user = new User({ name, email });
try {
await user.save();
res.status(201).json(user);
} catch (err) {
res.status(400).json({ message: err.message });
}
});

// Read Users
app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
res.status(500).json({ message: err.message });
}
});

// Update User
app.patch('/users/:id', async (req, res) => {
const { id } = req.params;
const { name, email } = req.body;
try {
const user = await User.findByIdAndUpdate(id, { name, email }, { new: true });
res.json(user);
} catch (err) {
res.status(400).json({ message: err.message });
}
});

// Delete User
app.delete('/users/:id', async (req, res) => {
const { id } = req.params;
try {
await User.findByIdAndDelete(id);
res.json({ message: 'User deleted' });
} catch (err) {
res.status(500).json({ message: err.message });
}
});

app.listen(PORT, () => {
console.log(Server is running on http://localhost:${PORT}); });

總結(jié)

通過本教程,你應該能夠理解如何使用Express.js構(gòu)建一個簡單的RESTful API,處理基本的CRUD操作。隨著對Express.js和RESTful API的理解深入,你可以進一步擴展其功能,增加用戶驗證、錯誤處理、文檔生成等功能,以滿足更復雜的應用需求。

本文章轉(zhuǎn)載微信公眾號@前端智能箱

上一篇:

基于NodeJS的KOA2框架實現(xiàn)restful API網(wǎng)站后臺

下一篇:

自定義mock數(shù)據(jù),實現(xiàn)restful風格api
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數(shù)據(jù)驅(qū)動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費