30分钟用Node.js构建一个API服务器的步骤详解

2020-06-17 06:09:31易采站长站整理


// note_routes.js
var ObjectID = require('mongodb').ObjectID;
module.exports = function(app, db) {
app.get('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
db.collection('notes').findOne(details, (err, item) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(item);
}
});
});
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
};

尝试使用一个笔记 ID,它应如下所示:

DELETE 路由

实际上删除对象与查找对象几乎相同。你只需用 remove 函数替换 findOne 即可。这是完整的代码:


// note_routes.js
// ...
app.delete('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
db.collection('notes').remove(details, (err, item) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send('Note ' + id + ' deleted!');
}
});
});
// ...

UPDATE 路由

最后一个! PUT 方法基本上是 READ 和 CREATE 的混合体。你找到该对象,然后更新它。如果刚才你删除了数据库中唯一的笔记,那就再创建一个!

代码:


// note_routes.js
// ...
app.put('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').update(details, note, (err, result) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(note);
}
});
});
// ...

现在你可以更新任何笔记,如下所示:

请注意这些代码还不完美 —— 比如你没有提供正文或标题,PUT 请求将会使数据库中的笔记上的那些字段无效。

API 完成

就这么简单!你完成了可以进行 CRUD 操作的 Node API。

本教程的目的是让你熟悉 Express、Node 和 MongoDB —— 你可以用简单的程序作为进军更复杂项目的跳板。