I am currently working on an express application that includes some articles stored in a Mongo database. As I wait for the mongoose model Article to load, the body of the request gets changed to:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /articles</pre>
</body>
</html>
and the status code is set to 404. To view the body being sent, I have implemented the following code snippet:
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;
This code was slightly modified from the one found here:
The code I am using is as follows:
Route
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);
});
Model
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;