0

I have an express application with some articles stored in a Mongo database. While I'm waiting for the mongoose model Article to load, the body of the request is 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 to 404. The code I'm using to see the body being sent is this:

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;

It's a slightly modified version of this one: https://stackoverflow.com/a/34712950/13300387

My code is this:

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;
asharpharp
  • 169
  • 1
  • 9

1 Answers1

0

in get method you can't get res.body you have to change router.get to router.post

xmilad
  • 1
  • 1
    I'm sorry if I misunderstand something, but I'm pretty sure get requests can get a response with a body, it's just that the request can't have a body. – asharpharp Aug 05 '22 at 08:57