-1

I am new to MongoDB and I started to make a test app which looks like this:

server.js

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var tasks = require('./routes/tasks');
var port = 8081;
var app = express();

// View Engine

app.set('views',path.join(__dirname,'views'));
app.set('view engine','ejs');
app.engine('html',require('ejs').renderFile);

// Set Static Folder

app.use(express.static(path.join(__dirname,'client')));

// Body parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : false}));
app.use('/',index);
app.use('/api',tasks);
app.listen(port,function(){

console.log('Server started at port : ' + port);
});

and my tasks file

tasks.js

var express = require('express');
var router = express.Router();

var mongojs = require('mongojs');
var db = mongojs('mongodb://user:pass@ds063186.mlab.com:63186/mytaskslist_ahsan',['tasks']);

router.get('/tasks',function(req,res,next){
db.tasks.find(function(tasks,err){
if(!err) res.json(tasks);
});
});

module.exports = router;

But when I try /api/tasks using Postman no response comes back. It keeps loading for a while and then says "Couldn't get any response". I also tried to console.log my db variable and it shows an empty object that means it's not connecting to DB.

Note I tried to connect to my local db instance and it works also my live connection string works in RoboMongo, but still not connecting using the code above.

Mika Sundland
  • 18,120
  • 16
  • 38
  • 50
Ahsan Attari
  • 987
  • 3
  • 12
  • 26

1 Answers1

1

Couldn't get any response says you dont respond to the request. If there is an error you dont send and log it. Give the error back with next and log it with an error logger.

db.tasks.find(function(tasks, err){
  if(err) {
    return next(err)
  }
  res.json(tasks);
});

And before app.listen

app.use((err, req, res, next) => {
  console.log(err.stack || err.message);
  if (res.headersSent)
    return next(err)
  res.status(500).send('Internal Server Error')
})

If you need further help post the error message

Julian
  • 2,724
  • 1
  • 15
  • 21
  • what it prints after implementing above `Internal Server Error` , but i don't see any error in my code – Ahsan Attari Oct 20 '16 at 19:55
  • Cou return this as an error message to the http request. The real error message is in console. That you dont reveal sensitive information – Julian Oct 20 '16 at 19:59
  • i think its not sensitive :-) , its simple `undefined` – Ahsan Attari Oct 20 '16 at 20:00
  • but it could be sensitive. undefined helps a lot. You dont actualy have an error, but the arguments are in the wrong order. First `err` then `tasks` – Julian Oct 20 '16 at 20:05
  • really , i mean really !!!!! . its unbelievable that i missed that little things , thanks Man !!!! it works – Ahsan Attari Oct 20 '16 at 20:07