MongoDB Connection Error with NodeJS - javascript

I am currently trying a simple Hello World App using MongoDB, Express, Swig and NodeJS
Using latest node, and other dependencies.
Chrome 46.0 (64 bit). Mac OS X 10.9.5
Below is my app.js code
var express = require('express'),
app = express(),
cons = require('consolidate'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
var mongoclient = new MongoClient(new Server("localhost", 27017, {'native_parser':false}));
var db = mongoclient.db('course');
app.get('/', function(req, res){
// Find one document in our collection
db.collection('hello_mongo_express').findOne({}, function(err, doc) {
if(err) throw err;
res.render('hello', doc);
});
});
app.get('*', function(req, res){
res.send('Page Not Found', 404);
});
mongoclient.open(function(err, mongoclient) {
if(err) throw err;
app.listen(8080);
console.log('Express server started on port 8080');
});
Below is the Error I get when node app.js:
AMAC02PC0PHG3QP:6_hello_world_express_swig_mongodb macadmin$ node app.js
Failed to load c++ bson extension, using pure JS version
/Users/macadmin/Desktop/NodeJS_MongoDB/6_hello_world_express_swig_mongodb/app.js:31
if(err) throw err;
^
Error: failed to connect to [localhost:27017]
at null.<anonymous> (/Users/macadmin/Desktop/NodeJS_MongoDB/6_hello_world_express_swig_mongodb/node_modules/mongodb/lib/mongodb/connection/server.js:553:25)
at emitThree (events.js:97:13)
at emit (events.js:175:7)
at null.<anonymous> (/Users/macadmin/Desktop/NodeJS_MongoDB/6_hello_world_express_swig_mongodb/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket.<anonymous> (/Users/macadmin/Desktop/NodeJS_MongoDB/6_hello_world_express_swig_mongodb/node_modules/mongodb/lib/mongodb/connection/connection.js:512:10)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at emitErrorNT (net.js:1250:8)
Some places it is saying to write 127.0.0.1 instead of local host.

Try
sudo npm rebuild
Some of the packages may not have been installed properly during the initial set up. Make sure port 27017 is not in use by some other process.

The bson module is maybe not correctly installed.
Try
npm install -g node-gyp
and then
npm update

Related

repl node js problem SyntaxError: Unexpected identifier

I am trying to learn node js.
so I used the below example and implemented in repl.
https://medium.freecodecamp.org/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2
but I am not able to run the app.
when I run the app I am getting the below error.
can you tell me how to fix it.
providing my code base below.
is there any online editor where I can run node js and see
https://repl.it/#doadhdoadh/IdleAccurateSource
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
require('./app/routes')(app, {});
app.listen(port, () => {
console.log('We are live on ' + port);
});
node v9.7.1 linux/amd64
npm dev
evalmachine.<anonymous>:1
npm dev
^^^
SyntaxError: Unexpected identifier
at new Script (vm.js:51:7)
at createScript (vm.js:136:10)
at Object.runInContext (vm.js:181:10)
at evaluate (/run_dir/repl.js:133:14)
at ReadStream.<anonymous> (/run_dir/repl.js:116:5)
at ReadStream.emit (events.js:180:13)
at addChunk (_stream_readable.js:274:12)
at readableAddChunk (_stream_readable.js:261:11)
at ReadStream.Readable.push (_stream_readable.js:218:10)
at fs.read (fs.js:2124:12)
I went through the original server.js file and found that you were missing a semicolon on line 12 i.e db = database.db("api");
Update
I just realised that the repl NodeJs demo gets triggered using index.js file. I just exported a function in server.js and imported it in index.js to trigger the server creation process.
Check the updated poc
Hope it works!

Connection error on curl in node.js

Hi I am currently trying to learn how to create a backend for my app but when trying to create a port 3000 and having curl it produces this error:
NodeTutorial git:(master) ✗ curl -v http://localhost:3000 - the connection is refused.
Please Help.
My code in my index.js is as follows:
var http = require('http'),
express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
app.get('/', function (req, res) {
res.send('<html><body><h1>Hello World</h1></body></html>');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Seems your server has not started, try running below steps and see if you are able to connect or not:
Step 1: Create a directory which will contain all the files related to our app and execute npm init:
$ mkdir nodejs-server
$ npm init
Step 2: Install Express as a dependency:
$ cd nodejs-server
$ npm install --save express
Step 3: Create default entry point for Node.js i.e index.js, inside the same directory we created:
$ cd nodejs-server
$ touch index.js
Copy the content you have shown in your question in index.js:
var http = require('http'),
express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
app.get('/', function (req, res) {
res.send('<html><body><h1>Hello World</h1></body></html>');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Step 4: Move to directory nodejs-server and start the app following below command:
$ cd nodejs-server
$ node index.js

Cannot GET /cool on Heroku nodejs tutorial locally

Here are the dependencies of my package.json file where i've added "cool-ascii-faces. I then need to update my index.js file to GET the /cool page so that on each reload I would see an ascii face. I'm getting a 404 error and it says 'Cannot GET /cool'
"dependencies": {
"ejs": "2.3.3",
"express": "4.13.3",
"cool-ascii-faces": "~1.3"
}
Below is my index.js file that calls declares cool
var cool = require('cool-ascii-faces');
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/cool', function(request, response) {
response.render('pages/index')
});
app.get('/cool', function(request, response) {
response.send(cool());
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
I then run npm install to update the dependencies and then heroku local, but get the 404 error.
Any help in the right direction would be great!
You're probably getting an exception when you start the node web server, due to a module dependency error.
Check your command/terminal window. If you see a red warning message pointing to your module.js file, you have an exception:
$ heroku local
forego | starting web.1 on port 5000
web.1 | module.js:341
In this case, you need to install the cool-ascii-faces module. In your 'node-js-getting-started' directory, use the following npm command to install:
$ npm i -S cool-ascii-faces
Also... you'll want to convert your index page route back to '/'. Your routes logic should look like this:
app.get('/', function(request, response) {
response.render('pages/index')
});
app.get('/cool', function(request, response) {
response.send(cool());
});
Otherwise, you'll always get the default 'pages/index' page when you hit the '/cool' route instead of a smiley face.
You don't have to include
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
}
Heroku will run "npm start" to start your server and dynamically choose the port. You don't have to specify port explicitly.
this problem happened for me. After I typed "git push heroku master", I typed "heroku open" and it worked.

Express has no method configure error

I'm trying to get started with the MEAN stack. And I'm following this tutorial: link
I have made it until the Test Our Server section. Here
// modules =================================================
var express = require('express');
var app = express();
var mongoose= require('mongoose');
// configuration ===========================================
// config files
var db = require('./config/db');
var port = process.env.PORT || 8080; // set our port
mongoose.connect(db.url); // connect to our mongoDB database (uncomment after you enter in your own credentials in config/db.js)
app.configure(function() {
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(express.logger('dev')); // log every request to the console
app.use(express.bodyParser()); // have the ability to pull information from html in POST
app.use(express.methodOverride()); // have the ability to simulate DELETE and PUT
});
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
app.listen(port); // startup our app at http://localhost:8080
console.log('Magic happens on port ' + port); // shoutout to the user
exports = module.exports = app; // expose app
When I run
nodemon server.js
I get this error
app.configure(function() {
^
TypeError: Object function (req, res, next) {
app.handle(req, res, next);
} has no method 'configure'
at Object.<anonymous> (C:\Users\Yuksel\Desktop\node\test\server.js:14:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
5 Mar 17:27:20 - [nodemon] app crashed - waiting for file changes before startin
g...
It simply says app has no method configure(I guess). But when I delete the configure part and run it again, it works.(This mean app has .listen method, so it is an express object.)
I have tried with both node and nodemon. And I couldn't figure it out. Thank you for your time.
Tom in his blog post new-features-node-express-4 provides examples of how to convert from using app.configure in express version 3.x to removing it in express version 4.0.
For convenience I added the code example below.
Version 3.x
// all environments
app.configure(function(){
app.set('title', 'Application Title');
})
// development only
app.configure('development', function(){
app.set('mongodb_uri', 'mongo://localhost/dev');
})
// production only
app.configure('production', function(){
app.set('mongodb_uri', 'mongo://localhost/prod');
})
Version 4.0
// all environments
app.set('title', 'Application Title');
// development only
if ('development' == app.get('env')) {
app.set('mongodb_uri', 'mongo://localhost/dev');
}
// production only
if ('production' == app.get('env')) {
app.set('mongodb_uri', 'mongo://localhost/prod');
}
The configure method has been removed from express as of version 4.0.0 (including 4.0.0-rc2). See the changelog at https://github.com/strongloop/express/blob/master/History.md#400--2014-04-09

error message when trying to install jquery with node.js

I am trying to use jQuery in a node.js application. It seems easy enough according to Can I use jQuery with Node.js? but when I tried to run npm install jQuery jsdom htmlparser xmlhttprequest and simply npm install jQuery neither one seemed to work for me. Here is the full text of the error message I got:
$ npm install jQuery jsdom htmlparser xmlhttprequest
npm http GET https://registry.npmjs.org/htmlparser
npm http GET https://registry.npmjs.org/jQuery
npm http GET https://registry.npmjs.org/xmlhttprequest
npm http GET https://registry.npmjs.org/jsdom
npm http 304 https://registry.npmjs.org/jsdom
npm http 304 https://registry.npmjs.org/htmlparser
npm http 304 https://registry.npmjs.org/xmlhttprequest
npm http 200 https://registry.npmjs.org/jQuery
npm http GET https://registry.npmjs.org/contextify
npm http GET https://registry.npmjs.org/cssom
npm http GET https://registry.npmjs.org/request
npm http 304 https://registry.npmjs.org/contextify
npm http 304 https://registry.npmjs.org/cssom
npm http 304 https://registry.npmjs.org/request
npm http GET https://registry.npmjs.org/bindings
npm http 304 https://registry.npmjs.org/bindings
> contextify#0.1.2 install /Users/nicmeiring/node_modules/jsdom/node_modules/contextify
> node-gyp rebuild
info it worked if it ends with ok
spawn python [ '/Users/nicmeiring/.node-gyp/0.6.14/tools/gyp_addon',
'binding.gyp',
'-I/Users/nicmeiring/node_modules/jsdom/node_modules/contextify/build/config.gypi',
'-f',
'make' ]
ERR! Error: not found: make
at F (/usr/local/lib/node_modules/npm/node_modules/which/which.js:43:28)
at E (/usr/local/lib/node_modules/npm/node_modules/which/which.js:46:29)
at Object.oncomplete (/usr/local/lib/node_modules/npm/node_modules/which/which.js:57:16)
ERR! not ok
npm WARN optional dependency failed, continuing contextify#0.1.2
xmlhttprequest#1.3.0 ./node_modules/xmlhttprequest
jquery#1.6.3 ./node_modules/jquery
htmlparser#1.7.5 ./node_modules/htmlparser
jsdom#0.2.13 ./node_modules/jsdom
├── request#2.9.200
└── cssom#0.2.3
In my node.js application file (app.js) I include the jquery module using var $ = require('jQuery), but, as expected, it returns an error when I try to use jQuery in my application. Any ideas what is causing the install to fail? Thanks
UPDATE:
the jquery module successfully installed but when I try to run my app I am getting a new error. Here are the scripts:
app.js
var express = require('express')
, routes = require('./routes')
, $ = require('jquery');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(require('stylus').middleware({ src: __dirname + '/public' }));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', routes.index);
app.get('/', routes.getData);
app.listen(4000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
and index.js
var $ = require('jquery');
exports.index = function(req, res){
console.log("rendering index.html")
res.render('layout', { title: 'Express' })
};
var link = "http://en.wikipedia.org/w/api.php?action=parse&format=json&callback=?"
exports.getData = $.ajax({
url: link,
dataType: JSON,
data: data,
success: function(data) {
console.log(data);
console.log(data.parse.text['*']);
}
});
and here is the error I am getting when I start up the app
Nic-Meirings-MacBook-Pro:Wiki2 nicmeiring$ node app
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
ReferenceError: $ is not defined
at Object.<anonymous> (/Users/nicmeiring/Sites/Wiki2/routes/index.js:16:19)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Module.require (module.js:354:17)
at require (module.js:370:17)
at Object.<anonymous> (/Users/nicmeiring/Sites/Wiki2/app.js:7:14)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
It seems you are missing "make" which comes with Developer Tools. Here is the related SO question:
https://stackoverflow.com/a/1470005/337504

Categories

Resources