The body in Express is set to "Cannot GET [route]" during the execution of asynchronous code

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;

Answer №1

When using the get method, accessing res.body is not allowed. To retrieve res.body, simply switch from router.get to router.post

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn the process of automatically copying SMS message codes to input fields in Angular17

After receiving the first answer, I made some changes to the code. However, when testing it with Angular, I encountered several errors. How can I resolve these issues? TS: async otpRequest() { if ('OTPCredential' in window) { const ab ...

How can you load elements via AJAX?

Using AJAX, I successfully load content from a PHP page. Now, my challenge is to access and interact with the dynamically loaded elements (such as buttons, forms, or divs). The code snippet that is causing issues: jQuery(document).ready(function() { $( ...

Can Facebox's settings be adjusted during runtime? If so, how can this be done?

Can Facebox settings be accessed and customized? For instance, I am interested in setting the location of the loading image dynamically as shown on line 4: <script type="text/javascript" src="<?php echo base_url(); ?>media/facebox/facebox.js" > ...

Leverage the Power of Mongoose Schema Across Various Files (mongoose)

I recently encountered an issue while trying to utilize my Permissions schema in two different files. The error message "Cannot overwrite 'example' model once compiled" keeps popping up. Query: How can I effectively employ my Permissions schema ...

Checking CORS permissions with a pre-flight OPTIONS request

During development, I implement a middleware called cors using the following syntax: app.use(cors({origin: 'http://localhost:8100'})); However, I have noticed that for every route request, two requests are being made as shown in the image below ...

Toggle the image and update the corresponding value in the MySQL database upon clicking

Looking to implement a feature that allows users to bookmark pages in my PHP application using JavaScript. The concept involves having a list of items, each accompanied by an image (potentially an empty star). When a user clicks on the image, it will upda ...

Creating a Custom Error Object in Feathersjs: A Step-by-Step Guide

If I were to throw a GeneralError when calling a service, how can I create an error object with the following structure: { "status": "Failed", "code": "500_1", "detail": "Something is wrong with your API" } I have attempted to add this in the error hook: ...

Determining the file path in HTML5

Can anyone help me with retrieving the file path using html5 javascript once a user selects a file? I require the file path for a specific scenario: In this case, the user uploads a file and pauses it (currently only supported by Mozilla browsers), then c ...

Is it possible to use JavaScript to click on a particular point or element within a canvas?

Is there a way to trigger a click at a specific point on a canvas without direct access to the code that generates it? I've attempted using coordinates, but haven't had any success. Any alternative suggestions would be appreciated. UPDATE: To pr ...

There was an issue encountered while trying to install Electron using the command 'npm install electron'

While attempting to install electron using npm install electron, I encountered the following error: 908 error code 1 909 error path C:\Users\name\Documents\name\Code\code\node_modules\gl 910 error command failed ... ...

Embed a React component seamlessly within HTML code

Hey there! I have a situation where I'm pulling valid HTML content from the database and I need to replace merge tags with working React components. The HTML is generated using a WYSIWYG editor. Let me give you an example: const link = <a onClick= ...

What are the steps to create a class diagram for a NodeJS application?

For my final year project, I am looking to develop an application using Node API. As we delve into drawing the class diagram, it occurs to me that unlike Java or C#, Node JS does not have a built-in class concept. What would be the most effective approac ...

Generating charts using JSON data with the help of JavaScript

Hi there! I have a JSON file shown in the first image and I would like to create a chart similar to the one in the second image using JavaScript (using any library). Can anyone provide me with a simple example code on how to achieve this? ...

Leveraging angular.extend() with controllers and function overrides

Currently, I am working with Angular 1.4.8 and attempting to expand a controller. The original controller and the expanding controller are quite similar, but there is a specific function that I aim to replace in the extending controller. angular.module(&a ...

Angular 6: Dealing with Type Errors in the HttpClient Request

I am encountering issues with my services. I am attempting to retrieve a list of media files (generated by NodeJS, which generates a JSON file containing all media items). Although I can successfully fetch the data, I am facing an error stating "Property & ...

Troubleshooting problem with jQuery attribute value assignment

I am currently working with text boxes that store data in local storage upon saving. $(".formFieldUserData").each(function () { var key = $(this).attr("name"); var value = $(this).attr("value"); localStorage.setItem(key, value); } However, I have c ...

Customize specific styles for individual divs one at a time (without the use of jQuery)

Can you assist me with this issue? I am trying to display the <span class="badge badge-light"><i class="fa fa-check-circle"></i></span> tag (initially set to "visibility: hidden") when clicking on a div with the class "role-box". He ...

Printing from a Windows computer may sometimes result in a blank page

Looking to incorporate a print button into an HTML page, I'm facing an issue. The majority of the content on the page should not be included in the printed version, so my approach involves hiding everything in print and then showing only the designate ...

What is the most efficient way to update all elements within an array in a MongoDB document to a specific value?

Imagine a scenario where I possess the subsequent document: { _id: ObjectId("5234cc89687ea597eabee675"), code: "xyz", tags: [ "school", "book", "bag", "headphone", "appliance" ], qty: [ { size: "S", num: 10, color: "blue" }, ...

Consistently logging in results in undefined user information in passport context (express/graphql)

Currently experimenting with integrating passport.js into a graphql endpoint demo For reference, here is the relevant code snippet: https://gist.github.com/Falieson/855abee65621191d78575b7f28b26191#file-passport-ts-L28 The 'loginUser' mutations ...