鍵.png)
ASP.NET Web API快速入門介紹
cd express-rest-api
npm init -y
npm install express body-parser mongoose
在上面的命令中,我們首先創(chuàng)建了一個新的項目文件夾,然后安裝了Express.js、body-parser(用于解析請求體)和mongoose(用于MongoDB交互)。
首先,我們要建立一個基礎的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操作。在這個例子中,我們將構(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));
接下來,我們需要定義用戶的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)在,回到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 });
}
});
現(xiàn)在,我們已經(jīng)實現(xiàn)了一個簡單的CRUD API,你可以使用Postman或cURL進行測試。
http://localhost:3000/users
):{
"name": "John Doe",
"email": "john@example.com"
}
http://localhost:3000/users
)。http://localhost:3000/users/{userId}
):{
"name": "Jane Doe",
"email": "jane@example.com"
}
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}
);
});
通過本教程,你應該能夠理解如何使用Express.js構(gòu)建一個簡單的RESTful API,處理基本的CRUD操作。隨著對Express.js和RESTful API的理解深入,你可以進一步擴展其功能,增加用戶驗證、錯誤處理、文檔生成等功能,以滿足更復雜的應用需求。
本文章轉(zhuǎn)載微信公眾號@前端智能箱