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.
答案 0 :(得分: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