Can't connect to mongo db via js - javascript

I wrote a code for integrating all types of social networking log ins with nodejs. Here is my server.js
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js');
// configuration ===============================================================
mongoose.connect(configDB); // connect to our database
// require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({ secret: '234545671290eftg5678qwer235623' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
//require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
config/database.js
module.exports = {
'url' : 'mongodb://localhost27017:' // looks like mongodb://<user>:<pass>#mongo.onmodulus.net:27017/Mikha4ot
};
When I run node server, I get the following error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: failed to connect to [[object Object]:27017]
at null.<anonymous> (/home/ajay/Desktop/NodeAuthentication/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:555:74)
at emit (events.js:106:17)
at null.<anonymous> (/home/ajay/Desktop/NodeAuthentication/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:156:15)
at emit (events.js:98:17)
at Socket.<anonymous> (/home/ajay/Desktop/NodeAuthentication/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:534:10)
at Socket.emit (events.js:95:17)
at net.js:834:16
at process._tickCallback (node.js:448:13)
I'm confused between these 2 lines:
var configDB = require('./config/database.js');
and
mongoose.connect(configDB); // connect to our database
Should I use
mongoose.connect(configDB.url); ??
How can I fix it?

There is a typo in config/database.js. You don't specify database name and colon must be between localhost and 27017:
module.exports = {
'url' : 'mongodb://localhost:27017/my-test-db' // looks like mongodb://<user>:<pass>#mongo.onmodulus.net:27017/Mikha4ot
};
In connect method you could put Object or String, so you should use it as propose in question:
mongoose.connect(configDB.url);

Related

Nodejs and mongodb connection error after upgrading Mongo

Am trying to build some Todo app using Express and mongodb but i have some problems with nodejs and mongo connection and i searched about it on internet but didn't get any solution for my problem.
When trying to connect to mongodb from node js as in this code:
// This to require Express framework to use it
const express = require('express');
const csrf = require('csurf');
const errorhandler = require('errorhandler')
// Loads the piece of middleware for sessions
const logger = require('morgan');
const favicon = require('serve-favicon');
const methodOverride = require('method-override');
// This is a middleware to handle requests and parse the forms
const bodyParser = require('body-parser');
const routes = require('./routes');
const tasks = require('./routes/tasks');
const http = require('http');
const path = require('path');
const mongoskin = require('mongoskin');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const db = mongoskin.db("mongodb://localhost:27017/todo");
// Define object of express
const app = express();
app.use((req, res, next) => {
req.db = {};
req.db.tasks = db.collection('tasks');
next();
});
// This makes us can access app name from any JADe template
app.locals.appname = "Todo App Express.js";
app.locals.moment = require('moment');
// set app port to 8081 port
app.set('port', 8081);
// these tells express where's project safe templates in, and tell what's
// their extension will be.
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
// show express favicon in browser
app.use(favicon(path.join('public', 'favicon.ico')));
// this will print requests in terminal
app.use(logger('dev'));
// using body parser to can parse requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride());
// to use CSRF we need cookie parser
app.use(cookieParser('CEAF3FA4-F385-49AA-8FE4-54766A9874F1'));
app.use(session({
secret: '59B93087-78BC-4EB9-993A-A61FC844F6C9',
resave: true,
saveUninitialized: true
}));
app.use( csrf() );
// to process LESS stylesheets into CSS ones
app.use(require('less-middleware')(path.join(__dirname, 'public')));
// to use other static files which inside public
app.use(express.static(path.join(__dirname, '/public')));
// to make csrf used in templates
app.use( (req, res, next) => {
res.locals._csrf = req.csrfToken();
return next();
});
app.param('task_id', (req, res, next, taskId) => {
req.db.tasks.findById(taskId, (error, task) => {
if (error) return next(error);
if (!task) return next(new Error('Task is not found.'));
req.task = task;
return next();
});
});
// homepage to show our todo homepage
app.get('/', routes.index);
// list all created tasks [in-progress ones]
app.get('/tasks', tasks.list);
// this to mark all task as completed in one step
app.post('/tasks', tasks.markAllcompleted);
// this to add new task
app.post('/tasks', tasks.add);
// this to mark specfic task as completed
app.post('/tasks/:task_id', tasks.markcompleted);
// this to delete specfic task by :task_id
app.delete('/tasks/:task_id', tasks.del);
// this to list all completed tasks
app.get('/tasks/completed', tasks.completed);
// this 404 error page to show it if user requested any route doesn't exist in our routes
app.all('*', (req, res) => {
res.status(404).send();
});
if ('development' == app.get('env')) {
app.use(errorhandler());
}
// create our server
http.createServer(app).listen(app.get('port'),
() => {
console.log('Express server listening on port ' + app.get('port'));
});
I go this error in terminal:
/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/mongo_client.js:804
throw err;
^
TypeError: Cannot read property 'apply' of undefined
at EventEmitter.<anonymous> (/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongoskin/lib/collection.js:51:21)
at Object.onceWrapper (events.js:272:13)
at EventEmitter.emit (events.js:180:13)
at /home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongoskin/lib/utils.js:134:27
at result (/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/utils.js:414:17)
at executeCallback (/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/utils.js:406:9)
at /home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/mongo_client.js:271:5
at connectCallback (/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/mongo_client.js:940:5)
at /home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/mongo_client.js:801:11
at process._tickCallback (internal/process/next_tick.js:112:11)
[nodemon] app crashed - waiting for file changes before starting...
And in my Firefox got :
Unable to connect
Firefox can’t establish a connection to the server at localhost:8081.
Using NodeJS V9.8.0 and mongodb v3.4.14
This was a problem even we faced and it seems it just has to do with the consequent versions of 'mongoskin'. Why don't you try and use mongodb ?
Saves time and a much better option!

Error: Missing Helper: "iff"

For some reason, I keep getting this error every time i try to use {{#iff}
Is this not rendering my page as handlebars? Did I use the {{#iff}} statement correctly?
My console prints this out:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
This is my handlebars(login.hbs):
<h1><span class="fa fa-sign-in"></span> Login</h1>
{{#iff message.length '>' 0}}
<div class="alert alert-danger">{{message}}</div>
{{/iff}}
This is my server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
const hbs = require('hbs');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js');
mongoose.connect(configDB.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'hbs'); // set up hbs for templating
// required for passport
app.use(session({
secret: 'ilovescotchscotchyscotchscotch', // session secret
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
app.listen(port);
console.log('The magic happens on port ' + port);
In routes.js:
app.get('/login', function(req, res) {
res.render('login.hbs', { message: req.flash('loginMessage') });
});

How can I make session variables accessible to sub application

I am building an api that will interface with the MongoDB database and have mounted it as a subapplication. I have defined a session variable in my server controller.
However, any time that the server files need to talk to the api files the session variables are never passed off.
Heres the app.js file
//app.js file
'use strict';
process.env.NODE_ENV = 'development';
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');
var helmet = require('helmet');
var app = express();
app.use(helmet());
var port = process.env.PORT || 3000;
mongoose.connect("mongodb://localhost:27017/striv4");
var db = mongoose.connection;
// mongo error
db.on('error', console.error.bind(console, 'connection error:'));
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: db
})
}));
app.use(flash());
// make user ID available in templates
app.use(function (req, res, next) {
res.locals.currentUser = {
username:req.session.username,
id: req.session.userId
};
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('secreter'));
app.use(logger('dev'));
var api = require('./app_api/routes/index');
var serverRoutes = require('./server/routes/index');
//static file middleware
app.use(express.static(__dirname + '/public'));
app.set('views',__dirname +'/server/views');
app.set('view engine','pug');
app.use('/',serverRoutes);
app.use('/api',api);
//custom error handler
app.use(function(error, req, res, next) {
res.status(error.status || 500);
res.send('Error: '+error.message);
});
app.listen(port);
console.log('Listening on port: '+port);
You've got the whole program listed so there is more than one way for this to have gone wrong. Here are my suggestions to fix this:
Check the version of express-session you've installed. (Just run npm ls in the terminal and in your root Node app folder where you're package.json file is). If it's equal to or greater than v1.5.0, you don't need the cookie-parser for sessions anymore. Comment out the app.use line for the cookie parser and see if this works.
If you still need cookie parser for some other reason, you should use the same secret for sessions and the cookie parser. In your code, you've set two different values for secret.
I've seen that the other big failure for sessions occurs if the session store is not correctly connected to your Node app. Cross-check that the database is available and working. In my experience, Express sessions will fail silently if it can't get to the DB.
Hope this helps.

Error: Cannot find module 'html' , Can't serve static files

I don't know what I touched but suddenly it stopped serving my static files.
I have the following architecture:
App
Routes
Models
public
views
css
js
server.js
The Error:
Error: Cannot find module 'html'
at Function.Module._resolveFilename (module.js:325:15)
...
at /Users/.../vintageAddiction/app/routes/indexRoutes.js:12:11
indexRoutes.js:
var express = require('express');
var passport = require('passport');
var indexRouter = express.Router();
indexRouter.route('/').get( function(req, res) {
res.render('index.html'); // load the index.ejs file
});
module.exports = indexRouter;
SERVER.JS:
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./app/config/configDB.js');
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
require('./app/config/passport')(passport); // pass passport for configuration
// routes ======================================================================
var routes = require('./app/routes/indexRoutes.js'); // load our routes and pass in our app and fully configured passport
var adminRoutes = require('./app/routes/adminRoutes.js');
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
// app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({ secret: 'vintageisthelaw' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use('/', routes);
app.use('/admin', adminRoutes);
// set static files location
// used for requests that our frontend will make
app.use(express.static(__dirname + '/public/'));
app.set('views', __dirname + '/public/views');
app.set('view engine', 'jade');
// launch ======================================================================
app.listen(port);
console.log('The magic happens on :\n\n http://localhost:'+ port+'\n\n');
link to server.js
I've seen something similar to :
app.use(express.static(__dirname + '/public/views/'));
But I don't really understand why is not working
Hope you can help me guys !
In express.js order of middleware declaration is very important. You must define express.static middleware earlier than any of the routes:
SERVER.JS:
.. require
// logger must be defined first if you want log all the requests
app.use(morgan('dev'));
// after that you should define express.static middleware
app.use(express.static(__dirname + '/public/'));
app.set('views', __dirname + '/public/views');
app.set('view engine', 'jade');
// cookie and body parser must be defined before passport and session middleware
app.use(cookieParser());
app.use(bodyParser());
app.use(session({ secret: 'vintageisthelaw' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
// your routes must be defined in the end
app.use('/', routes);
app.use('/admin', adminRoutes);
app.listen(port);
console.log('The magic happens on :\n\n http://localhost:'+ port+'\n\n');

CORS header not working in MEAN stack application

I am developing an application using the MEAN stack (Node.js, Express, AngularJS, and Mongoose). I have a basic understanding of the two. My API is running on a different port from my frontend, and because of this, I've included the CORS header in my API file. However, Chrome is still giving me this error:
XMLHttpRequest cannot load http://localhost:9000/#/.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
This is the header I've included in my API:
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
I have no idea where I'm going wrong. If it helps at all, I'm trying to load a user object in order to display information on a profile page. This is the code from my Profile Controller:
angular.module('angTestApp')
.controller('ProfileCtrl', function ($scope, $http) {
$http.get('http://localhost:8080/profile')
.success(function (user) {
$scope.user = user;
console.log(user);
});
});
EDIT
Here's my server.js file if that helps:
// server.js
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express'); // call express
var cors = require('cors');
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://test:test#novus.modulusmongo.net:27017/a3pemoGa')
var classroom = require('./app/models/classroom');
var article = require('./app/models/article');
var user = require('./app/models/user');
//From Tutorial
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser());
app.use(cors());
//app.use(express.static(__dirname + '/public'));
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
//From tutorial
// set up our express application
require('./app/config/passport')(passport); // pass passport for configuration
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
require('./app/API/routes')(app, passport);
//require('./app/API/general');
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
//exports = module.exports = app;
i resolved the cors issue with tricky solution . first create the the route of scrape like this with require "REQUEST" npm
app.get('/scrape', function (req, res) {
console.log("=============================Scrape =========================")
var url = req.body.url;
request(url, function(error, response, html){
if(!error){
res.send(html)
}
});
and in the frontend use like this
$http.get("/scrape", {
params: { "url": "http://localhost:8080/profile" }
});

Categories