socket.io keeps 404ing? - node.js

sorry for the silly question and im sure its a noob mistake. I am following the how to use for socket io: http://socket.io/#how-to-use and keep having an problem;
I have a node app (running version 3.0 alpha of express) and have the following:
app = express()
io = require('socket.io').listen app
I have edited the layout.jade and added:
script(src="/socket.io/socket.io.js")
I have also run npm install socket.io and confirmed that it starts fine on the server.
If I browse to any page, console keeps showing:
GET http://localhost:3000/socket.io/socket.io.js 404 (Not Found)
Anyone else experienced this issue?

Here are step by step instructions I just tested them
express socket
cd socket
npm install
npm install socket.io
Add the following in app.js
var io = require('socket.io').listen(app);
Run
node app
In the console you should see
info - socket.io started
In the browser go to
http://localhost:3000/socket.io/socket.io.js
You should see the raw JavaScript
Edit:
I'm also having problems with 3.0alpha1. Looks like a bug. Here is an ugly work around
var fs = require('fs');
app.get('/socket.io/socket.io.js', function(req, res) {
fs.readFile('/PROJECT_HOME/node_modules/socket.io/lib/socket.io.js', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
}
else {
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.end(content, 'utf-8');
}
});
});

Are you runnning layout.jade from the app.js?
app.get('/',function(req,res){
res.sendfile('index.html');
});
This needs to be included in the app.js assuming your template is in index.html file.

Related

Can i use node as webserver for html app?

I'm sorry to ask such a simple question. I've been sent files by someone, an index.html file which pulls in a js file within script tags. I have to start a webserver to get through authentication and view the files (am in dev).
In my CLI i have navigated to the directory containing index.html. I have checked with node -v that I have it installed globally (yes, v 8.6). I've run the simple command node and checked my browser at http://localhost:3000 and a few other ports but get no joy. I've also tried node index.html but CLI throws an error.
How do i start the webserver? All the examples online tell me to build a .js file, but this is not an option.
Steps to set up a node web server
Create the route folder from your local machine.
Go to the command prompt from the project root path.
Install express using the command npm install express
Create server.js file
create the folder wwww and create the Index.html inside it.
server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/www'));
app.listen('3000');
console.log('working on 3000');
Index.html
<!doctype html
<html>
<head>
<title> my local server </title>
</head>
<body>
<h1> server working </h1>
<p> just put your html,css, js files here and it work on your own local nodejs server </p>
</body>
</html>
Go to the project root path and take the command prompt, then start the server by running the command node server.js
Then go to the browser and run the url localhost:3000.
Now you can see the html page will render on your browser.
Since you don't want to build a backend but just an http server.
I would propose to use an npm package that do just what you need:
Open a console
npm install http-server -g
Go to your "index.html" folder (in the console) then type:
http-server
Then reach your content in your browser at this address:
http://localhost:8080
Documentation here:
https://www.npmjs.com/package/http-server
Yes, this is possible.
A very simple example of how to do this would be to create file, let's call it app.js and put this in it:
const http = require('http'), // to listen to http requests
fs = require('fs'); // to read from the filesystem
const app = http.createServer((req,res) => {
// status should be 'ok'
res.writeHead(200);
// read index.html from the filesystem,
// and return in the body of the response
res.end(fs.readFileSync("index.html"));
});
app.listen(3000); // listen on 3000
Now, run node app.js
Browse to http://localhost:3000
There's loads of other npm packages that will help you out do this, but this is the simplest 'pure node' example to literally read index.html and serve it back as the response.
Its very easy to start a server using node js
Create a server.js file,
const http = require('http')
const fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(3000);
Run node server.js
Here is a reference
This will even solve your backslash issue by this

Localhost not working with node.js and socket.io

I am trying to learn the basics of node.js and socket.io. I have been using this tutorial http://tutorialzine.com/2012/08/nodejs-drawing-game/
the full code for this problem can be seen in the link above.
I can create a basic web server with node.js and get it to return hello world so I am sure that's installed correctly. However upon installing these packages
npm install socket.io#0.9.10 node-static
and setting up the serverside js as instructed
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
nstatic = require('node-static');
var fileServer = new nstatic.Server('./');
app.listen(8080);
I just get this prompt in my cmd and a constantly hanging web browser, instead of the html page that is meant to be served.I think I may have messed up an install but upon looking at the list of installed packages in npm it states both socket.io and node-static are present.
The code below should be more effective?, it looks like you are missing the handler part. The response must be explicitly ended or browser requests will hang forever like you are seeing. The node-static file.serve method manages the request once you pass it down. The source for .serve is here: https://github.com/cloudhead/node-static/blob/master/lib/node-static.js#L164
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
nstatic = require('node-static');
app.listen(8080);
var file = new nstatic.Server('./');
function handler(request, response) {
request.addListener('end', function () {
file.serve(request, response);
}).resume();
}
console.log('started')
Note also that the default file to serve to responses at / is index.html.

Express.js App on Phusion Passenger - did not write a startup response in time

I am trying to run an express.js app on a server running Phusion Paggenger (apache) and am seeing the error "An error occurred while starting the web application: it did not write a startup response in time." after the request times out. I've read through https://github.com/phusion/passenger/wiki/Debugging-application-startup-problems but this seems a bit obscure. My express app is as bare-bones as possible so I'm wondering if anyone knows if there may be a component specific to express that might cause this. I have been able to run a plain node.js app with the same setup on the server.
If you used the express-generator command to set up your project, you might see if pointing your Virtual Host configuration file's PassengerStartupFile line to bin/www instead of app.js does the trick instead of explicitly calling app.listen in the app.js file. Phusion Passenger's documentation does not address this specific convention adopted by ExpressJS. You can read some about this bin/www startup convention on Express's Moving to 4.x guide. Seemed to work for me.
It seems that you need to explicitly call app.listen within app.js. Specifically, I do this only when in production:
if (app.get('env') === 'production') {
app.listen(3000);
}
at the end of app.js
If you are getting here from google. This is now documented with Passenger: https://www.phusionpassenger.com/library/indepth/nodejs/reverse_port_binding.html
A working example of a simple express app is below:
if (typeof(PhusionPassenger) != 'undefined') {
PhusionPassenger.configure({ autoInstall: false });
}
var express = require('express');
var app = express();
app.get('/', function(req, res){
var body = 'Hello World';
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Length', body.length);
res.end(body);
});
if (typeof(PhusionPassenger) != 'undefined') {
app.listen('passenger');
} else {
app.listen(3000);
}

Include Node.JS + Socket.IO in Symfony2 application

I have done many researches and it seems I can't find the proper solution. I am confident in PHP. I also have done some tutorials on Node.JS and Socket.IO and I'm currently learning Symfony2 but I can't see how I can merge the two to achieve my goal.
My goal is to set up real-time notification for back-end users of my app. This app is a e-commerce website and I want the admin behind the scenes to be warned as soon as an order is made by a visual notification in the upper right corner of the admin panel. My server use FreeBSD.
My plan is to use Node.JS and Socket.IO to achieve this. If there is a better plan, I'm willing to hear about it. Otherwise, I cannot find proper resources to tell me how I can include Node.JS and Socket.IO to a Symfony2 app. I use composer to install bundles but I haven't used NPM with Symfony2.
I have found this question, this link and this other question to help me out but none of these tell me how I can install Node.JS in a Symfony2 app.
If someone could help me with the steps to complete to make me start developping this feature, I'd be glad.
Thanks!
For those who might be interested in the answer:
$ su -
Install Node.JS
$ cd /usr/ports/www/node
$ make install clean
Install NPM
$ cd /usr/ports/www/npm
$ make install clean
Install Socket.IO
$ cd /path/to/your/project/js/public/files
$ npm install socket.io
Develop the code
app.js
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {
fs.readFile('./index.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.on('newOrder', function () {
socket.broadcast.emit('message', 'Nouvelle commande');
});
});
server.listen(4321);
Front-end
<script src="{{ asset('http://localhost:4321/socket.io/socket.io.js') }}"></script>
<script>
jQuery(function($) {
var socket = io.connect('http://localhost:4321');
$('form').on('submit', function() {
socket.emit('newOrder', '1');
});
});
</script>
Back-End
<script>
jQuery(function($) {
var socket = io.connect('http://localhost:4321');
socket.on('message', function(message) {
alert(message);
});
});
</script>
Launch server
$ node app.js
That's all!

Unable to get connect-livereload to work with express server in gulp task

I am working off of Yeoman's gulp-webapp generator. I have modified my gulp serve task to use my Express server, rather than the default connect server it ships with. My issue is with Livereload functionality. I am trying to simply port the connect-livereload to work with my Express server rather than having to install new dependencies. It's to my understanding that most connect middleware should work fine with Express, so I am assuming connect livereload is compatible with Express 4.
Here are the contents of the relevant tasks in my gulpfile:
gulp.task('express', function() {
var serveStatic = require('serve-static');
var app = require('./server/app');
app.use(require('connect-livereload')({port: 35729}))
.use(serveStatic('.tmp'));
app.listen(3000);
});
gulp.task('watch', ['express'], function () {
$.livereload.listen();
// watch for changes
gulp.watch([
'app/*.ejs',
'.tmp/styles/**/*.css',
'app/scripts/**/*.js',
'app/images/**/*'
]).on('change', $.livereload.changed);
gulp.watch('app/styles/**/*.css', ['styles']);
gulp.watch('bower.json', ['wiredep']);
});
gulp.task('styles', function () {
return gulp.src('app/styles/main.css')
.pipe($.autoprefixer({browsers: ['last 1 version']}))
.pipe(gulp.dest('.tmp/styles'));
});
gulp.task('serve', ['express', 'watch'], function () {
require('opn')('http://localhost:3000');
});
With this simple setup, when I run gulp serve in my cmd everything spins up fine and I can accept requests at http://localhost:3000.
Now if I go and change the body's background color from #fafafa to #f00 in main.css and hit save, my gulp output will respond with main.css was reloaded, as seen in the bottom of this screenshot.
However, my webpage does not update. The background color is still light-grey instead of red.
Is there perhaps a conflict between my express server config and the way gulp handles its files? Is my Express server forcing the use of app/styles/main.css rather than the use of .tmp/styles/main.css? Shouldn't the livereload script handle the injection of the new temporary file?
Thanks for any help.
EDIT:
I was able to move forward a bit by adding livereload.js to the script block of my index file, like so:
<script src="http://localhost:35729/livereload.js"></script>
I am now able to get live changes pushed to the client. Why was this file not getting injected before? How can I ensure this is getting used programatically as opposed to pasting it into my files?
I was able to get past this issue by removing the app.use(require('connect-livereload')({port: 35729})) from my gulpfile, along with a couple of other lines, and having that instantiate in my Express server's app.js file.
My gulpfile's express task now looks like this:
gulp.task('express', function() {
var app = require('./server/app');
app.listen(3000);
});
I added in the connect-livereload just above where I specify my static directory in Express:
if (app.get('env') === 'development') {
app.use(require('connect-livereload')());
}
app.use(express.static(path.join(__dirname, '../app')));
Once I started using this setup, I was getting the livereload.js script injected into my document, and client-side changes are now auto-refreshed just how I wanted.
Hope this helps someone!

Resources