Express: router.route continues processing without sending the request

I've implemented the following code in my Express application:

var express    = require('express');        // Initializing Express
var app        = express();                 // Creating our app using Express
var bodyParser = require('body-parser');
var mongoose   = require('mongoose');
 // Connecting to the database
mongoose.connect('mongodb://username:pwd@<url>/db-name');

var Bear = require('./app/models/bear');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        // Setting up the port

var router = express.Router();   

// Middleware for all requests
router.use(function(req, res, next) {
    // Logging
    console.log('Something is happening.');
    next(); // Proceeding to the next route
});

router.route('/bears')

  .get(function(req, res) {
    Bear.find(function(err, bears) {
        if(err)
            res.send(err);
        console.log('I am in GET');
        res.json(bears);
    });
  })
  .post(function(req, res) {
    var bear = new Bear();
    bear.name = req.body.name;
    console.log('Body Param:'+ bear.name);
    bear.save(function(err) {
        if(err)
            res.send(err);

        res.json({ message: 'Bear created!'});
    });
  });

router.get('/', function(req, res) {
    res.json({ message: 'Hooray! Welcome to our API!' });
});

app.use('/api', router);


app.listen(port);

Here is my Model code:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var BearSchema = new Schema({
    name: String
});

module.exports = mongoose.model('Bear', BearSchema);

When I make a request using POSTMAN or the browser, it keeps loading indefinitely without returning anything. I believe the callback needs to be terminated but I'm not sure how to do that.

The URL I'm accessing is http://localhost:8080/api/bears and the request doesn't seem to complete.

Server output when hitting /api/bears and the request stalls:

Something is happening.

Output from server when visiting /api

Something is happening.

And on the browser, I see:

Cannot GET /api

Answer №1

The issue I encountered was related to the mongooose version specified in my package.json file. After updating to the latest version, 4.1.11, and running a npm install, the problem was resolved. More information on this bug can be found here: https://github.com/meanjs/mean/issues/1010

To ensure that no errors occurred and the connection was successful, I included the following code snippet:

mongoose.connect('mongodb://db-name:pwd@mongourl:port/db', function(err) {
   if(err) {
     console.log(err);
   } else {
     console.log('success');
   }
 });

Upon testing, I received the following error message:

{ [MongoError: auth failed] name: 'MongoError', ok: 0, errmsg: 'auth failed', code: 18 }

I then utilized RoboMongo for connecting to the database successfully using the SCRAM-SHA-1 authentication mechanism. I delved into specifying the authentication as an option in my URL which led me to the mentioned bug report.

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

Is it possible to utilize AngularJS' ng-view and routing alongside jade?

Currently, I am diving into the world of the MEAN stack. I noticed that Express utilizes jade by default, but I decided to experiment with it even though I can easily use html instead. When attempting to route with Angular, like so: ... body div(ng-view ...

What is the best method for updating audio from a source in Vue.js?

Forgive me if this is a silly question, but I'm still learning the ropes here. I may be going about this in all the wrong ways! I created a backend that learns from a text file and generates sentences along with an audio version of those sentences. I ...

The initial click does not trigger a state update in React

I attempted to create a straightforward system for displaying data with two sorting buttons (ascending & descending). My approach involved fetching and displaying data from an array using the map method. In a separate component file, I utilized useEffect ...

Issue with Vue 3 where radio input remains unchecked after being clicked

I'm currently facing an issue with radio buttons for answers in my questions. Whenever I click on an answer, the radio input does not stay checked and I am unable to disable the other options. My front-end is developed using Vue 3 and the back-end wit ...

Tips for moving and filling data in a different component using NextJS

Currently, I am developing an application using Next.js and tailwindcss. The Issue In essence, I have a table consisting of 4 columns where each row contains data in 3 columns and the last column includes an "Update" button. The data in each row is genera ...

Steps to switch the primary audio input

Is there a way to change the default microphone of a client based on user selection? I can obtain the list of devices using the enumerateDevices promise, but how can 'Audio 40 USB' be set as the default microphone in this scenario? navigator.me ...

Having trouble with string matching in JavaScript?

My attempts to verify my Ajax response with a string have consistently resulted in a fail case being printed. Below is the section of code relating to my ajax request: var username = document.getElementById("name").value; var password = document.getEle ...

Our frontend application currently utilizes REST API for authentication, but we are eager to enhance it by integrating Google login functionality through Firebase

Dealing with tokens from Firebase can be tricky, especially since they are generated differently than those from REST APIs. This poses a challenge when it comes to authenticating users who log in using Google. The token issued by Firebase is not compatibl ...

Tips for generating a universal regulation in vee-validate version 3

Is it possible to create a universal validation rule that can be applied to multiple elements? universalRule: { required:'required', min:'min', etc.. } On the form <ValidationProvider name="universalRule" rules=&qu ...

Vue.js <v-data-table> - Automatic sorting/ custom sorting options

I am trying to arrange the numerical data in a Vue.js data-table in descending order right from the start. I want it to look like the screenshot provided below. Screenshot of My Desired Result The data that needs to be arranged in descending order is the ...

The tooltip for the Google+ button stopped working

After setting up my Portfolio, I added a Google+ button. However, the page lacks styling and there seems to be an issue with the tooltip causing delays. Can anyone help me identify where the problem lies? ...

Accessing the JSON file from the Google Maps Places API using either JavaScript or PHP

In the midst of developing an application, I am working on fetching a list of places near a specific latitude and longitude. After obtaining an API key, inputting it into the browser URL successfully retrieves a JSON file containing the desired places dat ...

When a form contains a ViewChild element, changes to the ViewChild element do not automatically mark the

Let's set the stage: MainComponent.html <form #someForm > <input type="text" name="title" [(ngModel)]="mainVar" /> <child-component /> <input type="submit" [disabled]="someForm.form.pristine" /> </form> ChildComp ...

Ways to connect a button to a Bootstrap 5 tab class

I am trying to find a way to directly link to a specific tab using a Bootstrap 5 button class. I have attempted to incorporate the solution provided in the following resource: Twitter Bootstrap 5 Tabs: Go to Specific Tab on Page Reload or Hyperlink Unfo ...

Struggling with modifying class in HTML using JavaScript

I've been attempting to replicate a JavaScript code I came across on the internet in order to create a functioning dropdown menu. The concept is quite straightforward - the div class starts as xxx-closed and upon clicking, with the help of JavaScript, ...

Error: Oops! The super expression can't be anything other than null or a function in JavaScript/TypeScript

I am facing an issue with class inheritance in my code. I have a class A that extends class B, which in turn extends class C. Whenever I try to create a new instance of class A within a function, I encounter the following error message: Uncaught TypeError: ...

Passing image source from parent component to child component in Vue.js

I encountered an issue where I stored the image file name in a variable within the parent component and passed it to the child component using props. However, despite this setup, the child element is not displaying the image as expected. Here is the data ...

The href attribute in a stylesheet link node is malfunctioning

When setting up my website, I experimented with two different methods. 1) The first method involved using node to run the server. 2) The second method simply used an index.html file on my local computer. Interestingly, I noticed a difference in how the s ...

When the res.json function is used to return data, the Date type object automatically gets converted into

Upon creating a date object with var myDate = new Date(), I run into an issue. Whenever I return it using res.json({msg: {myDate: myDate}}), the myDate object is automatically converted into a string. My goal is to maintain the type of myDate without it ...

What is the reason behind the unnecessary requirement of adding {...props} when passing them to a component in a React router?

Recently, I delved into learning React and encountered a puzzling issue while following a course. To gain clarity, I decided to experiment with it separately, but the confusion remains unresolved. While researching, I discovered that when utilizing a Rout ...