执行异步代码时,Express将body设置为Cannot GET[route]



我有一个express应用程序,其中一些文章存储在Mongo数据库中。当我在等待猫鼬模型文章加载时,请求的正文被更改为:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /articles</pre>
</body>
</html>

并且将状态代码设置为404。我用来查看发送的尸体的代码是这样的:

function logResponseBody(req, res, next) {
var oldWrite = res.write,
oldEnd = res.end;

var chunks = [];

res.write = function (chunk) {
chunks.push(new Buffer(chunk));
res.body = Buffer.concat(chunks).toString('utf8');

oldWrite.apply(res, arguments);
};

res.end = function (chunk) {
if (chunk) chunks.push(new Buffer(chunk));

res.body = Buffer.concat(chunks).toString('utf8');

oldEnd.apply(res, arguments);
};

next();
}

module.exports = logResponseBody;

这是一个稍微修改过的版本:https://stackoverflow.com/a/34712950/13300387

我的代码是:

路线

router.get("/", async (req, res, next) => {
console.log(res.body); //undefined
console.log(res.statusCode); //200
const articles = await ArticleModel.find();
console.log(res.body); //...Cannot GET /articles...
console.log(res.statusCode); //404
res.status(200).json(articles);
});

型号

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ArticleSchema = new Schema({
title: {
type: String,
required: true,
unique: true
},
description: {
type: String,
required: true
},
type: {
type: String,
required: true
}
}, {collection: "articles"});
const ArticleModel = mongoose.model('article', ArticleSchema);
module.exports = ArticleModel;

在get方法中,您无法获得res.body你必须更改路线。转到路线。张贴

最新更新