error in socket.io code execution - node.js

From the Digital Ocean Community at this url, https://www.digitalocean.com/community/tutorials/how-to-install-express-a-node-js-framework-and-set-up-socket-io-on-a-vps, I encounter an eroor when trying to execute Part 4: The Server Code. The article states "Go and open up the app.js file in the Express application folder. Inside you'll a bunch of auto-generated code, delete all of it and use the following example instead:"
Here is the code:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, http = require('http');
var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server); // this tells socket.io to use `our express server`
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
console.log("Express server listening on port 3000");
When I make these changes to app.js and then try to execute the app I get the following error:
/root/socketio-test/app.js:9
var app = express();
^
TypeError: object is not a function
at Object.<anonymous> (/root/socketio-test/app.js:9:11)
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
I have no idea how to correct this error.
System info: Ubuntu LEMP on 14.04
node.js installed, express installed, socket.io installed.

I believe you have some how installed the wrong version of express..
Do a express --version before express 3.x express was not a function.
I tried to install npm install express -g on a new droplet and I cannot get express to be an executable.
As far as I understand the express skeleton generator was moved into a separate package which can be installed using npm install express-generator -g
Which will give you the command line executable express, after you install express-generator you should be good to go.
http://expressjs.com/en/starter/generator.html
I think DO needs to update their tutorial.

Related

Integrating Angular with Nodejs

I tried to connect angular front end with nodejs earlier I ran ng build on public folder of app and then ran localhost:3000. No error was given on compilation but app is broken now. Now do I achieve it? My folder structure is like this
client
public
app.js
client contains all angular code, public contains compiled code of angular
till I have also changed output path to ../public in angular.json.
And here is my app.js:
var express = require('express');
var path= require('path');
var cors = require('cors');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var passport = require('passport');
var app= express();
var port = 3000;
app.set('view engine','ejs');
//app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, '/views'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', routesApi);
app.get('/', (req,res) => {
res.send("Invalid page");
});
app.listen(port, () => {
console.log(`Starting the server at port ${port}`);
});
I think up to now you have a build of a running angular application and perfectly running node.js server.
What you have to do is host your client application. Follow the following steps to get this working.
Install http-server globally on your machine using npm install http-server -g command
Then run http-server /path/to/your/dist/folder. (You should get a dist folder after running ng build --prod)
Then run your node.js server.
And open your browser and go to http://localhost:8080

how to check if i have mongodb installed on my computer

I'm trying to create a RESTful API using Node.js and MongoDB for the first time. I'm new to back end programming.
For some reason am getting this error
module.js:327
throw err;
^
Error: Cannot find module './routes/api'
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (C:\xampp\htdocs\rest\server.js:15:17)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
[nodemon] app crashed - waiting for file changes before starting...
I am unsure whether MongoDB is installed correctly, but I don't know how to check that.
Please help me, either with the error or how I can to check that I have installed MongoDB correctly.
Here is my server.js
// DEPENDENCIES
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
// MongoDB
mongoose.connect('mongodb://localhost/rest_test');
// EXPRESS
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// ROUTES
app.use('/api', require('./routes/api'));
// START SERVER
app.listen(3000);
console.log('API is working on port 3000')
First you need to run MongoDB on your machine use command mongod (if you have a path to mongod.exe in your System PATH Variable)
Install all dependencies for your project with npm install express mongoose body-parser
And Error: Cannot find module './routes/api' Where your api.js file ?
After that you can run your server use node server.js
Since I do not see your file api.js I write it myself for clarity
server.js
// DEPENDENCIES
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
// MongoDB
mongoose.connect('mongodb://localhost/rest_test');
// EXPRESS
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// ROUTES
app.use('/api', require('./routes/api'));
// START SERVER
app.listen(3000);
console.log('API is working on port 3000')
routes/api.js
module.exports = function(app, res) {
res.sendFile(process.cwd() + '/routes/index.html');
}
routes/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>Hello Node.js</h1>
</body>
</html>
Assuming that you are on Windows:
Check in your program files in C:\ to look for a Mongo folder
To use mongo, you need to start a server on your machine.
To do this, launch mongod.exe in the mongo folder you have found previously.
It should work after the server is started!

how to install new nodejs modules to expressjs project?

Currently I am working on online yaml code editor. I use expressjs framework for it. I want to install yamljs module to it. How do I install it? Because following code line cause to an error.
var YAML = require('yamljs');
This is the code segment
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var YAML = require('yamljs');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
This is the error
Error: Cannot find module 'yamljs'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/tharindu/Documents/projects/Group project2/CuubezFinal/app.js:12:12)
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 Module.require (module.js:364:17)
I use webstorm for coding. I have installed yamljs module using
npm install yamljs
This library is perfectly using if I run my code manually from the ubuntu terminal. But When I run the expressjs project, It gives above error.
could you provide more information like the error text?
Have you tried
npm install yamljs
to make the module accessible to the node environment?
This library is perfectly using if I run my code manually from the
ubuntu terminal. But When I run the expressjs project, It gives above
error.
Make sure your node_modules folder is available in the same or a more outer directory than the folder of your executing script.

Mustache and Express in Node

I'm trying desperately to tie in the mu2 module into Express in node.js. However, I can't seem to figure it out, and when trying to run the example using the mu2express module, I keep getting this error when trying to run:
module.js:340
throw err;
^
Error: Cannot find module 'mu2Express'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (/myapp.js:1:80)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
Is this an error caused by something locally, or with the module itself? Right now, I'm using the node http module to work with mu2 exclusively, but I really want to use express is possible.
Can anyone out there help? Is there more information I should provide? I'm very new to node.js and I could use some direction if possible!
Look into consolidate:
https://github.com/visionmedia/consolidate.js/
It is made by the man behind Express himself and has support for Hogan and Handlebars.
EDIT:
You can initialize Express with this for consolidate
var express = require('express');
var cons = require('consolidate');
var app = express();
app.engine('html', cons.hogan);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
Renders will now be served from /views with HTML extension and Mustache-flavor syntax.
app.get('/', function (req, res) {
res.render('index', {msg: 'Hello world!'}
});
And a basic template, again just mustache-flavor syntax
Hello {{msg}}
You're requiring the mu2Express module from the myapp.js file, so you need to install it first.
You'll need to create a package.json file with at least the following content:
{
"name": "myProject",
"version": "0.0.1",
"dependencies": {
"mu2express": "~0.0.1"
}
}
And I'm not sure, that the examples are good for this project, you may need to require mu2express instead of mu2Express.

node.js + express 3 + socket.io = Can't set headers after they are sent

I'm new to learning node.js and seem to have run into an error that can't get to fix.
Its a very simple and beginners code so shouldn't need much explanation, more over it works fine on localhost, but breaks on production server.
App.js
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 8000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
var server = app.listen(8000);
var io = require('socket.io').listen(server);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
And here's the dreaded error!
http.js:644
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:644:11)
at ServerResponse.res.setHeader (/home1/artalatc/public_html/cloud1/node_modules/express/node_modules/connect/lib/patch.js:59:22)
at next (/home1/artalatc/public_html/cloud1/node_modules/express/node_modules/connect/lib/proto.js:153:13)
at Function.app.handle (/home1/artalatc/public_html/cloud1/node_modules/express/node_modules/connect/lib/proto.js:198:3)
at Server.app (/home1/artalatc/public_html/cloud1/node_modules/express/node_modules/connect/lib/connect.js:66:31)
at Manager.handleRequest (/home1/artalatc/public_html/cloud1/node_modules/socket.io/lib/manager.js:564:28)
at Server.<anonymous> (/home1/artalatc/public_html/cloud1/node_modules/socket.io/lib/manager.js:118:10)
at Server.EventEmitter.emit (events.js:115:20)
at HTTPParser.parser.onIncoming (http.js:1793:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:111:23)
Problem seems to be at var io = require('socket.io').listen(server); because commenting this like removes the error.
What version of Node are you using?
I had the same problem when I was using 0.9.x. I downgraded Node to 0.8.4 and the problem seems to have gone away.
My best guess is something in Node has changed that Socket.io doesnt agree with.
upgrade
express - 3.1.0 and socket.io - 0.9.13
it's ok on nodejs0.10
Which version of express are you using? Check out https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x or try this:
var server = app.listen(8000);
var io = require('socket.io').listen(server);
i was having the same issue mate
if you are using express 3.0 you should try this:
http://codehenge.net/blog/2012/08/using-socket-io-with-express-3-x/
also check your version of node:
node --version
try using v0.8.9 or any other stable version
It helped me! And will help you
For anyone bumping in to this issue you should be using:
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
As express no longer returns a HTTP instance that socket.io requires. See the updated README.md file on https://github.com/learnboost/socket.io for the express 2 and 3 examples.
This approach works in the current stable release 0.8.14:
var express = require('express')
, app = express()
, server = app.listen(8000)
, io = require('socket.io').listen(server);
I had the exact same issue. Incompatible versions of express and socket.io were to blame. Upgraded them to express 3.2.4 and socket.io 0.9.14 and works like a charm.
Or you can downgrade your socket.io to a previous version, but you'll have to figure that one out.
this error come because express internally use cache means for every second request data get from cache so it response back with 304 status code so use
app.disable('etag');
it tells the express each request fresh means with stautscode 200
Change socket.io dependency to 0.9.15 in package.json, run npm install and it should fix your problem.
Run a npm list socket.io
Make sure it doesn't show invalid as below,
─ socket.io#0.9.10 invalid
npm ERR! invalid: socket.io#0.9.10 c:\Users....
If you get this error, npm install socket.io.
Also make sure the same with other packages.

Resources