facing difficulty in creating my server through nodejs express - node.js

I am a beginner in Node js and Express and I was trying to create my server following this tutorial : https://codeforgeek.com/express-nodejs-tutorial/
This is my server.js code:
var express = require("express");
var app = express();
var server = app.listen(3000, function() {
console.log("We have started our server on port 3000");
});
error on cmd

It seems like it's the use of the ejs package without following the next steps of the tutorial, I get the same error at Step 3:
We have started our server on port 3000
/..stackhelp/59715144/node_modules/express/lib/application.js:119
this._router.handle(req, res, function(err) {
^
TypeError: Cannot read property 'handle' of undefined
at Function.app.handle (/Users/tamebadger/Projects/stackhelp/59715144/node_modules/express/lib/application.js:119:15)
at Server.app (/Users/tamebadger/Projects/stackhelp/59715144/node_modules/express/lib/express.js:28:9)
at emitTwo (events.js:125:13)
at Server.emit (events.js:213:7)
at parserOnIncoming (_http_server.js:602:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)
Removing the ejs package would solve your problem if it was an option (you need it later in the tutorial)
Our of interest sake, see if you still get the issue if you add the next part of the tutorial:
app.get('/',function(req,res){
res.send('Hello world');
});

Related

error in electron js when implementing express js

I'm trying to build a desktop application using electron js .I want to integrate express js in my application .when I try to start my application,I'm facing this error
[Main Instruction]
A JavaScript error occured in the browser process
[Content]
Uncaught Exception:
Error: listen EADDRINUSE :::3000
at Object.exports._errnoException (util.js:814:11)
at exports._exceptionWithHostPort (util.js:837:20)
at Server._listen2 (net.js:1214:14)
at listen (net.js:1250:10)
at Server.listen (net.js:1340:5)
at EventEmitter.listen (C:\Users\Kobbi\WebstormProjects\untitled14\node_modules\express\lib\application.js:617:24)
at Object.<anonymous> (C:\Users\Kobbi\WebstormProjects\untitled14\index.js:17:18)
at Module._compile (module.js:428:26)
at Object.Module._extensions..js (module.js:446:10)
at Module.load (module.js:353:32)'
here is my code:
var BrowserWindow = require('browser-window')
var express = require('express');
var app = express();
app.use(express.static(__dirname));
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
app.on('ready', function() {
var mainWindow = new BrowserWindow({
width: 800,
height: 600
})
mainWindow.loadUrl('http://localhost:3000')
})
I would appreciate any help ,thanks in advance
app.on('ready') ... 'app' is not your express app.
this should be electron app.
Example:
var app = require('app');
BrowserWindow = require('browser-window');
express = require('express');
expressApp = express();
May be express use 'app' variable and electron also uses it.
Normally the EADDRINUSE error means, that your port is already beign used (probably by an instance of your express webserver). Maybe your electron app didn't close properly, and you have to kill to manually to also kill the webserver that is accessing the port.

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

Error 'Can't set headers after they are sent' only on Cloud9

I am getting following error while using Express and socket.io together on Cloud9 ide:
http.js:707
throw new Error('Can\'t set headers after they are sent.'); ^ Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:707:11)
at ServerResponse.res.setHeader (/var/lib/stickshift/523075494382ec51c3000001/app-root/data/610464/node_modules/express/node_modules/connect/lib/patch.js:59:22)
at next (/var/lib/stickshift/523075494382ec51c3000001/app-root/data/610464/node_modules/express/node_modules/connect/lib/proto.js:153:13)
at Function.app.handle (/var/lib/stickshift/523075494382ec51c3000001/app-root/data/610464/node_modules/express/node_modules/connect/lib/proto.js:198:3)
at Server.app (/var/lib/stickshift/523075494382ec51c3000001/app-root/data/610464/node_modules/express/node_modules/connect/lib/connect.js:65:37)
at Manager.handleRequest (/var/lib/stickshift/523075494382ec51c3000001/app-root/data/610464/node_modules/socket.io/lib/manager.js:564:28)
at Server. (/var/lib/stickshift/523075494382ec51c3000001/app-root/data/610464/node_modules/socket.io/lib/manager.js:118:10)
at Server.EventEmitter.emit (events.js:117:20)
at HTTPParser.parser.onIncoming (http.js:2056:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:120:23)
Below is my server.js code:
var express = require('express');
var app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
server.listen(process.env.PORT, process.env.IP);
app.get('/', function(req,res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World\n');
})
I am using node: "0.10.x", socket.io: "0.9.14" and express: "3.x". This error is coming only on Cloud9 ide. On localhost it runs fine.
Please help.
I ran into this exact same problem. Although it's not a good solution, reverting Express back to version 3.1.0 solved this for me. It appears at a high level that the latest versions of Express and Socket.io don't play nicely together.
The versions I am using after reverting are:
Node: 0.10.x,
Socket.io: 0.9.16,
Express: 3.1.0

Mongoose connect method fails on simple Node Server. Express, Mongoose, Path

This is the first time I'm running node with mongoose. I'm following some tutorials in this backbone book and I'm up to this chapter on creating a restful api using express, mongoose and I'm following the code exactly I've even come to copying and pasting but it's still not working. Here is the code:
http://addyosmani.github.io/backbone-fundamentals/#creating-the-back-end
// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
path = require( 'path' ), //Utilities for dealing with file paths
mongoose = require( 'mongoose' ); //MongoDB integration
//Create server
var app = express();
// Configure server
app.configure( function() {
//parses request body and populates request.body
app.use( express.bodyParser() );
//checks request.body for HTTP method overrides
app.use( express.methodOverride() );
//perform route lookup based on url and HTTP method
app.use( app.router );
//Where to serve static content
app.use( express.static( path.join( application_root, 'site') ) );
//Show all errors in development
app.use( express.errorHandler({ dumpExceptions: true, showStack: true }));
});
//Start server
var port = 4711;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});
// Routes
app.get( '/api', function( request, response ) {
response.send( 'Library API is running' );
});
//Connect to database
mongoose.connect( 'mongodb://localhost/library_database');
//Schemas
var Book = new mongoose.Schema({
title: String,
author: String,
releaseDate: Date
});
//Models
var BookModel = mongoose.model( 'Book', Book );
I've been poking around on stack overflow and other sites trying to resolve the issue but nothing I found seemed to allow me to connect to the mongodb.
The first error is:
events.js:72
throw er; // Unhandled 'error' event
^
Error: failed to connect to [localhost:27017]
at null.<anonymous> (/Users/jeff/Sites/backbone-ex2/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:536:74)
at EventEmitter.emit (events.js:106:17)
at null.<anonymous> (/Users/jeff/Sites/backbone-ex2/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15)
at EventEmitter.emit (events.js:98:17)
at Socket.<anonymous> (/Users/jeff/Sites/backbone-ex2/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:478:10)
at Socket.EventEmitter.emit (events.js:95:17)
at net.js:411:14
at process._tickCallback (node.js:415:13)
This change seems to fix that issue:
mongoose.connect( 'mongodb://localhost/library_database', function(err) { if (err) console.log(err); } );
After that express works but mongodb fails to connect:
Express server listening on port 4711 in development mode
[Error: failed to connect to [localhost:27017]]
I tried changing to this:
mongoose = require( 'mongoose' ).Mongoose;
I also tried running mongod in the cli with some variations on options in the cli but that seems to just bring up the help page. I'm totally stuck... Any help would be greatly appreciated. Thanks in advance.
You need to actually successfully get mongod running and listening for connections. Just type mongod with no options, hit ENTER, and let it run. Then in a separate terminal start your express app. Note that mongod is the mongodb server daemon whereas mongo is the command line client where you can run an interactive REPL and issue database commands.
You need to install the database itself. Refer here for mongodb installation guide.

Resources