我正在尝试设置一个简单的 CRUD 应用程序。我已经在 express 中设置了 DELETE 路由,我正在尝试使用 Postman 来访问它。
当我在请求中记录 req.body 时,我得到一个空对象。
路线:
var router = express.Router();
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
};
username = process.env.MONGODB_USERNAME;
password = process.env.MONGODB_PASSWORD;
const MongoClient = require('mongodb').MongoClient;
const connectionString = `mongodb://${username}:${password}@localhost:27017`
/* DELETE post delete. */
router.delete('/', (req, res) => {
const postId = req.body.postId;
console.log(req.body);
console.log(postId);
MongoClient.connect(connectionString, {useUnifiedTopology: true})
.then(client => {
console.log("Delete request to database!");
const db = client.db("blog");
const postsCollection = db.collection('blogPosts');
postsCollection.findOneAndDelete({"_id": postId})
.then(deletedDocument => {
if(deletedDocument) {
console.log(`Successfully deleted document that had the form: ${deletedDocument}.`)
res.send(`Successfully deleted document that had the form: ${deletedDocument}.`);
} else {
console.log("No document matches the provided query.")
res.send("No document matches the provided query.");
}
return deletedDocument
})
.catch(err => console.error(`Failed to find and delete document: ${err}`));
})
.catch(error => console.error(error));
});
module.exports = router;
Express app.js:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var postRequestRouter = require('./routes/postrequest');
// var adminRouter = require('./routes/admin');
var postDeleteRouter = require('./routes/postdelete');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/postrequest', postRequestRouter);
// app.use('/admin', adminRouter);
app.use('/postdelete', postDeleteRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
生成的控制台日志:
{}
undefined
Delete request to database!
Successfully deleted document that had the form: [object Object].
DELETE /postdelete 200 43.848 ms - 7
我知道对 MongoDB 本身的请求可能会失败,因为它的格式不正确,但现在我只是想了解为什么 req.body 是空的。
任何帮助将不胜感激!