问题:帮我用express写一个后端接口,给前端用来查询post,可以对post进行增删改查,后端连着mongodb数据库。
好的,我来为您编写一个简单的Express后端接口,可以供前端使用来查询post,并且可以对post进行增删改查操作。具体实现如下:
首先我们需要安装必要的依赖:express
, mongodb
和body-parser
。您可以在项目根目录下通过执行以下命令进行安装:
npm install express mongodb body-parser --save
接下来,我们需要创建一个app.js
文件,并在其中引入所需的依赖:
const express = require('express');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const app = express();
const port = 3000;
接着,我们需要连接到 MongoDB 数据库。在此之前,您需要确保已经启动了 MongoDB 服务。您可以在控制台中执行以下命令进行启动:
mongod
然后,我们可以通过以下代码连接到数据库:
const url = 'mongodb://localhost:27017';
const dbName = 'mydb';
MongoClient.connect(url, function(err, client) {
console.log("Connected successfully to server");
const db = client.db(dbName);
const collection = db.collection('posts');
// 在这里编写接口代码
client.close();
});
接下来,我们需要编写我们的接口代码。我们将提供以下 RESTful API:
- GET /api/posts:获取所有的 post
- GET /api/posts/:id:根据 ID 获取特定的 post
- POST /api/posts:创建一个新的 post
- PUT /api/posts/:id:根据 ID 更新一个已有的 post
- DELETE /api/posts/:id:根据 ID 删除一个已有的 post
下面是代码实现:
// 获取所有的 post
app.get('/api/posts', function (req, res) {
collection.find({}).toArray(function(err, docs) {
res.send(docs);
});
});
// 根据 ID 获取特定的 post
app.get('/api/posts/:id', function (req, res) {
const postId = req.params.id;
collection.findOne({_id: new ObjectID(postId)}, function(err, doc) {
if (doc == null) {
res.sendStatus(404);
} else {
res.send(doc);
}
});
});
// 创建一个新的 post
app.post('/api/posts', jsonParser, function (req, res) {
collection.insertOne(req.body, function(err, result) {
res.send(result.ops[0]);
});
});
// 根据 ID 更新一个已有的 post
app.put('/api/posts/:id', jsonParser, function (req, res) {
const postId = req.params.id;
collection.findOneAndUpdate(
{_id: new ObjectID(postId)},
{$set: req.body},
{returnOriginal: false},
function(err, result) {
if (result.value == null) {
res.sendStatus(404);
} else {
res.send(result.value);
}
}
);
});
// 根据 ID 删除一个已有的 post
app.delete('/api/posts/:id', function (req, res) {
const postId = req.params.id;
collection.findOneAndDelete(
{_id: new ObjectID(postId)},
function(err, result) {
if (result.value == null) {
res.sendStatus(404);
} else {
res.sendStatus(204);
}
}
);
});
最后,我们需要监听端口并启动应用程序,代码如下:
app.listen(port, function () {
console.log(`App listening on port ${port}!`);
});
完整的app.js
代码如下:
const express = require('express');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
const app = express();
const port = 3000;
const jsonParser = bodyParser.json();
const url = 'mongodb://localhost:27017';
const dbName = 'mydb';
MongoClient.connect(url, function(err, client) {
console.log("Connected successfully to server");
const db = client.db(dbName);
const collection = db.collection('posts');
// 获取所有的 post
app.get('/api/posts', function (req, res) {
collection.find({}).toArray(function(err, docs) {
res.send(docs);
});
});
// 根据 ID 获取特定的 post
app.get('/api/posts/:id', function (req, res) {
const postId = req.params.id;
collection.findOne({_id: new ObjectID(postId)}, function(err, doc) {
if (doc == null) {
res.sendStatus(404);
} else {
res.send(doc);
}
});
});
// 创建一个新的 post
app.post('/api/posts', jsonParser, function (req, res) {
collection.insertOne(req.body, function(err, result) {
res.send(result.ops[0]);
});
});
// 根据 ID 更新一个已有的 post
app.put('/api/posts/:id', jsonParser, function (req, res) {
const postId = req.params.id;
collection.findOneAndUpdate(
{_id: new ObjectID(postId)},
{$set: req.body},
{returnOriginal: false},
function(err, result) {
if (result.value == null) {
res.sendStatus(404);
} else {
res.send(result.value);
}
}
);
});
// 根据 ID 删除一个已有的 post
app.delete('/api/posts/:id', function (req, res) {
const postId = req.params.id;
collection.findOneAndDelete(
{_id: new ObjectID(postId)},
function(err, result) {
if (result.value == null) {
res.sendStatus(404);
} else {
res.sendStatus(204);
}
}
);
});
app.listen(port, function () {
console.log(`App listening on port ${port}!`);
});
});
最新回复