Home > database >  browser keeps loading forever when getting data from Mongodb using node.js
browser keeps loading forever when getting data from Mongodb using node.js

Time:10-30

i was trying to make a very simple MEAN STACK app that just gets books names, prices from a mongodb request but when i type the url to get the data it just keeps loading forever in the browser here's the main code

const express = require("express") ; 
const mongoose = require("mongoose") ;
cors = require('cors') ;
const path = require('path') ;
bodyParser = require('body-parser') ;
const app = express() ; 
const port = 3000 ;
const booksRoute = require('./routes/api') ;

// enable cross-origin sharing and ...
app.use('/api',booksRoute) ;
app.use(cors()) ; 
app.use(express.static(path.join(__dirname,'dist/smart-bookshelf'))) ;
app.use('/',express.static(path.join(__dirname,'dist/smart-bookshelf'))) ;
app.use(bodyParser.json()) ;
app.use(bodyParser.urlencoded({
  extended:false 
})) ;

mongoose.connect('localhost:27017/books',()=>console.log("connected successfully to database !")) ;

const server = app.listen(3000,()=>{console.log("server is working correctly on port : " port)}) ;

// error handler
app.use(function (err, req, res, next) {
  console.error(err.message); // Log error message in our server's console
  if (!err.statusCode) err.statusCode = 500; // If err has no specified error code, set error code to 'Internal Server Error (500)'
  res.status(err.statusCode).send(err.message); // All HTTP requests must have a response, so let's send back an error with its status code and message
});

and here's the route code

mongoose = require('mongoose') ;
const express = require('express') ;
const BookModel = require('../models/bookModel');
const booksRoute = express.Router() ;

booksRoute.route('/').get((req,res)=>{
    BookModel.find((error,data)=>{
        if (error){
            console.log("an error accured while retrieving data !") ; 
        }
        else{
            res.json(data) ;
        }
    })
}) ;

module.exports = booksRoute ; 

https://github.com/mohamedalimani/bookshelf

CodePudding user response:

In your route handler, if you encounter an error, you don't send any response and thus the browser would just sit there for a long time waiting for a result to come back (eventually, it will timeout). Your error handler won't automatically get the error unless you send it the error.

I'd suggest changing your route handler to this:

booksRoute.route('/').get((req, res, next) => {
    BookModel.find((error,data)=>{
        if (error) {
            next(error);
        } else {
            res.json(data) ;
        }
    })
});

CodePudding user response:

SOLVED IT : the problem was in this line of code mongoose.connect('localhost:27017/books',()=>console.log("connected successfully to database !")) ; that's the wrong database url. it should be this instead 'mongodb://localhost:27017/books'

  • Related