Node.js server will not start but seems to connect to DB - node.js

I have a node application that is not working though did work about 2 hours ago (no code changes). Also no changes to the server, I only ran another node application on the same port but that process has been killed.
Command to start node node server
server.js
var app = require('./server/index');
app.set('port', process.env.PORT || 3000);
var server = app.listen(8080, function() {
console.log('Express server listening on port ' + server.address().port);
});
app.js (stripped down)
const express = require("express"),
mongoose = require("mongoose"),
app = express();
mongoose.connect(config.db, {autoReconnect: true}, (err) => {
if (!err) console.log('MongoDB has connected successfully.');
});
mongoose.connection.on('error', function() {
console.error('MongoDB Connection Error. Make sure MongoDB is running.');
});
var authRoutes = require('./routes/auth.js');
authRoutes(app, passport);
module.exports = app;
Output when starting node process
(node:4341) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:4341) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
MongoDB has connected successfully.

Solved it, seems that using node server was going directly into my server directory and running app.js file note the server.js file I wanted it to. Instead I had to run node server.js

Related

AWS EC2 NodeJS doesn't respond

I've got an AWS EC2 MEAN instance up and running (partially). The app is a RESTful JSON service and as far as I can tell is up and running as expected:
var app = require('./app');
var port = process.env.PORT || 3000;
var server = app.listen(port, function() {
console.log('Express server listening on port ' + port);
});
console output:
node server.js
Express server listening on port 3000
Db.prototype.authenticate method will no longer be available in the
next major release 3.x as MongoDB 3.6 will only allow auth against
users in the admin db and will no longer allow multiple credentials on
a socket. Please authenticate using MongoClient.connect with auth
credentials.
I've also added the Inbound Security Group for port 3000
testing the API out in the browser is where I run into problems... If I attempt to GET a list of objects using http://ec2-XX-XX-XX-XX.com:3000/belts the call eventually times out. However when I try a GET for a single object using http://ec2-XX-XX-XX-XX.com:3000/belts/some_id_here I get a valid 200 response with the expected object.
Of course everything works as expected locally. What am I missing?
Thanks in advance
//edit with requested code formatted :)
//app.js
var express = require('express');
var app = express();
var BeltController = require('./controller/BeltController');
app.use('/belts', BeltController);
//Belt Controller
router.get('/', function (req, res) {
Belt.find({}, function (err, belts) {
if (err) {
return res.status(500).send("There was a problem finding the Belt. " + err);
}
res.status(200).send(belts);
});
});

MongoDB connections on Windows 2008 r2 error: getaddrinfo ENOTFOUND

I am writing a MEAN application for work and I have come up to a roadblock. My index.js file, which contains my mongo db connection information, seems to be wrong and I am scratching my head to find the solution. Unfortunately all similar issues I see are on the 'nix side. I am not very well versed in Windows so if this is a stupid question, I apologize.
Current index.js file:
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var _ = require('lodash');
var dbURI = 'mongodb:127.0.0.1\d$\db\pclistapp';
// Create the app
var app = express();
// Add middleware necessayr for the REST API
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method_Override'));
// Connect to MongoDB
mongoose.connect(dbURI);
//var db = mongoose.connection;
// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', function () {
console.log('Mongoose default connection open to ' + dbURI);
});
// If the connection throws an error
mongoose.connection.on('error',function (err) {
console.log('Mongoose default connection error: ' + err);
});
// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
console.log('Mongoose default connection disconnected');
});
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose default connection disconnected through app termination');
process.exit(0);
});
});
// Test connection
mongoose.connection.once('open', function() {
console.log('Listening on port 3000... ');
app.listen(3000);
})
Output when I try and run node index.js is MonogError: getaddrinfo ENOTFOUND mongodb mongodb:127. The DB is currently running on port 27017.
I have tried
mongodb:\\"PCname"\d$\db\pclistapp
mongodb:\\localhost\d$\db\pclistapp
mongodb:"PCname"\d$\db\pclistapp
mongodb:localhost\d$\db\pclistapp
and none of them seem to work. I know the UNC works for \"PCname"\d$\db\pclistapp so I am not sure what the issue is.
DB Connection Issue
DB Operational
Took a long time but the mistake was simple. I re-wrote the code to condense the errors and it's not a UNC which I need to connect to but via HTTP. Fix that and I was off to the races.
Silly me.
Code:
var mongoURI = "mongodb://localhost:27017/pclistapp";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
console.log("mongodb connection open");
});

Running nodejs, expressjs, socket.io application on a real server not working

I'm able to successfully run nodejs, expressjs, socket.io and mongodb appplication on my local machine http://localhost:3000
Now, I have uploaded the application on the real server that supports nodejs but how can I run the application using the port 3000? So www.mywebsite.com/MyApp:3000 doesn't work :( Do I have to run in a PORT?
can you please help me?
Here's my server app.js code:
var express = require('express');
var mongoose = require ('mongoose');
var app = express();
app.use('/', express.static('../app/'));
app.use('/bower_components', express.static('../bower_components/'));
var http = require('http').Server(app);
var io = require('socket.io')(http);
//mongodb databse
mongoose.connect ('mongodb://127.0.0.1/mydb', function (err) {
if (err) {
console.log (err);
} else {
console.log ("Connected to mongodb");
}
});
io.sockets.on ('connection', function (socket) {
console.log("hello world, I'm running fine!")
});
http.listen(3000, function () {
'use strict';
});
EDIT: if I use port 80, I get this error:
events.js:87
throw er; // Unhandled 'error' event
^
Error: listen EACCES
at exports._errnoException (util.js:748:11)
at Server._listen2 (net.js:1123:19)
at listen (net.js:1166:10)
at Server.listen (net.js:1251:5)
....etc
To run your app on production using your existing node / express code you would naviagate to http://www.mywebsite.com:3000/MyApp (assuming your firewall allows port 3000)
You can change the port though to be what ever you want by changing this part of the code:
http.listen(3000, function () {
'use strict';
});
The standard port for web is 80. So you could change this to be
http.listen(80, function () {
'use strict';
});
And then use your url as normal - http://www.mywebsite.com/MyApp
Note: If you have another web server on your server that is using this port already then you are going to have a problem as it will not listen until the port is free. You will have to disabled other web servers listening on port 80 first.
Non-privileged user (not root) can't listen on sockets on ports below 1024 either.

mongoose never stops loading

I am on windows. The local database is running fine, I can write to and find collections with the mongo command line tool. The local nodejs is running fine as well. When I remove my mongoose code, I can reach my endpoints.
When I start the node server with the mongoose code, I get this message:
23:05:57 web.1 | started with pid 20860
23:05:58 web.1 | { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
23:05:58 web.1 | js-bson: Failed to load c++ bson extension, using pure JS version
23:05:58 web.1 | Node app is running at localhost:5000
The server starts, although the error is worrisome (have tried to fix it for a good while, no luck yet), but it doesn't seem like a fatal error.
When I try to access one of my endpoints, either through Postman API, the browser or my application, it tries to connect forever. I can also see in mongo that a connection to the db never is made.
This is the code I have right now:
var express = require('express');
var app = express();
var mongoose = require('mongoose');
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
mongoose.connection.on("open", function(ref) {
console.log("Connected to mongo server.");
return start_up();
});
mongoose.connection.on("error", function(err) {
console.log("Could not connect to mongo server!");
return console.log(err);
});
mongoose.connect("mongodb://localhost/test");
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
app.get('/', function(request, response) {
response.send("Hello StackOverflow");
});
I've been sitting quite a few hours over the last three days trying to make it work, feels like I've been through every remotely relevant google search at this point. Hope you can help me out. :)
EDIT: If I go with mongoose version 3.8.3. The MODULE_NOT_FOUND error disappears. But it doesn't fix the never ending load.

app.set('port' , process.env.port || 3000) typeerror object #<object> has no method 'set' at object.<anonymous>

I am using Express 4.2.0 and node.js 0.10.12.
The weird thing is that I created a project in C\program files\node\nodetest and when I did npm start I got no errors.
Now I created a project in C\program files\node\secondtest and when I do npm start I get
app.set('port' , process.env.port 3000) typeerror object #<object> has no method 'set' at object.<anonymous> and its pointing in C\program files\node\secondtest\bin\www:5:5
Truth is , I dont know how to deal with this error, because I dont get what it means. Is it because both my projects listen on port 3000?
I just started secondtest , I installed succesfully the dependencies with npm install and added this in app.js
var http = require('http');
var express = require('express');
var app = express();
http.createServer(app).listen(3000, function() {
console.log('Express app started');
});
app.get('/', function(req, res) {
res.send('Welcome!');
});
Thanks
EDIT
If I leave the default code in app.js and www I get no errors. If I replace the default code of app.js with mine, and I remove the
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
part from www, then I get no errors.
Because I guess app.set and app.get are depricated in express 4.2.0? Or because when I set an http server in my app.js code, conflicts the default www code? Either one of these, or I am really confused.
EDIT 2
This is the default code of the www
#!/usr/bin/env node
var debug = require('debug')('secondtest');
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
Updated answer according to the updated question.
Since you're calling www and its code needs to set the port and listen to it, your secondtest code should not listen to the port. Instead it should export the Express app as follows:
// ...
module.exports = app;
The www will do the listening part.
Otherwise, the secondtest tries to start listening on a port while not exporting the Express app, and www tries to listen again on a variable app which is not an Express app, thus the error object #<object> has no method 'set'.
When you do var app = require('../app'); in another script, it is important so that this ../app script actually exports the Express app.
Old answer.
Do node app.js instead of using npm command.
Second, make sure the same port is not used by both processes at the same time. You can't listen to the same port unless you're in cluster mode.
Considering the following is the content of both firsttest and secondtest:
var http = require('http');
var express = require('express');
var app = express();
http.createServer(app).listen(process.env.port || 3000, function() {
console.log('Express app started');
});
app.get('/', function(req, res) {
res.send('Welcome!');
});
Do the following to start both apps:
Terminal 1: (the first app will default to port 3000).
$ node firsttest/app.js
Terminal 1:
$ export PORT=3001
$ node secondtest/app.js

Resources