I'm having a newbie problem with using express. I'm using Ubuntu 14.04 and make a new dir and run "express" in the terminal and it sets up a project template. Then run "npm install" to install the dependencies. And then edit 'views/layout.jade' to change "!!!" to "doctype html" as the node error suggests when trying to run the server without change.
Afterward, I start the server by entering "node app.js" on terminal and am then able to see the default page in my browser by using "localhost:3000" or "192.168.1.13:3000".
My understanding is that I should be able to use "192.168.1.13:3000" from another computer in the local network. However when I try this I get "connecting to 192.168.1.13..." for about 30 seconds to a minute then it says "The connection has timed out ... The server at 192.168.1.13 is taking too long to respond."
I've tried this from firefox and chrome on both windows desktop and android phone. I also tried setting it to port 80 instead of 3000 with the same result. I've tried adding "'0.0.0.0'," after the port in app.listen but this has same result as well.
I have never set up or messed around with firewalls or port forwarding in this Ubuntu installation so I believe those shouldn't be the issue? (is the problem with my router?) Maybe I'm wrong here.
Here's the relevant files-
app.js:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes');
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(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.listen(3000, function(){
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
routes/index.js:
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: 'Express' })
};
views/layout.jade:
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body!= body
views/index.jade:
h1= title
p Welcome to #{title}
Let me know if I've left anything out. Cheers.
I resolved this by opening incoming port 3000 with iptables as suggested by slebetman, with the following command:
iptables -I INPUT 1 -p tcp --dport 3000 -j ACCEPT
Related
Ok im having problems yet again with socket.io and express. When I run my node js application it begins to build before hitting an error " GET http://localhost:3000/socket.io/socket.io.js 404 (Not Found) " and "Uncaught ReferenceError: io is not defined" This is my second time working with web sockets and receiving the same error. For the previous app I fixed this problem by setting up a reverse proxy on my apache server. It looked like this;
ProxyPass /socket.io http://localhost:3000/socket.io
However for current nodejs app this is not fixing the issue. The main difference between these two applications is that the current app does not start working with socket.io until the user directs themself to the localhost:3000/bomber-kids-online game page. The current app is an extension of the first app aka this nodejs app provides a website along with my previous app which is a game hosted at zEyeland.com/bomber-kids-online.
Here is a look at my js file that sends the browser the proper html file to load:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require('express');
var router = express.Router();
var updatedMAP;
var updatedOBJECTS;
router.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log("a user connected");
socket.on('sendNoramlBomb', function(xPosition, yPosition, power){
socket.broadcast.emit('sendNoramlBomb', xPosition, yPosition,
power);
});
socket.on('sendRedBomb', function(xPosition, yPosition, power){
socket.broadcast.emit('sendRedBomb', xPosition, yPosition, power);
});
socket.on('sendBlueBomb', function(xPosition, yPosition, power){
socket.broadcast.emit('sendBlueBomb', xPosition, yPosition,
power);
});
socket.on('sendGreyBomb', function(xPosition, yPosition, power){
socket.broadcast.emit('sendGreyBomb', xPosition, yPosition,
power);
});
socket.on('sendGreenBomb', function(xPosition, yPosition, power){
socket.broadcast.emit('sendGreenBomb', xPosition, yPosition,
power);
});
socket.on('sendPlayer', function(locationY, locationX, direction){
io.emit('sendPlayer',locationY, locationX, direction);
});
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
socket.on('disconnect', function(){
console.log("user disconnected");
});
});
//http.listen(3000, function(){
// console.log('listening on *:3000');
//});
module.exports = router;
This is the apache configuration for my current project
ProxyPass /socket.io http://localhost:3000/bomber-kids-online/socket.io
ProxyPassReverse /socket.io http://localhost:3000/bomber-kids-online/socket.io
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyRequests Off
ProxyPreserveHost On
ProxyPass / http://localhost:3000/
ProxyPassReverse / http://localhost:3000/
So to recap on whats going on. Im trying to run a nodejs game that uses websockets. When visit my game on website at localhost:3000/bomber-kids-online it get an ( GET http://localhost:3000/socket.io/socket.io.js 404 (Not Found) ) How do i fix this issue? My reverse proxy will not seem to fix it this time. You can view a working version of my game at zeyeland.com/bomber-kids-online. My current project uses the exact same html and javascript files to run. However by examining my reverseProxy above you will notice that in my current project the game is not being accessed from localhost:3000 directly but from a route which is provided from another js file on server.
Here is how my app first js file looks like;
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var bomberKidsRouter = require('./routes/games/bomber-kids-online-
game');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/bomber-kids-online', bomberKidsRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
The issue is that express and socket.io are not sharing the same server.
I'm not seeing any server.listen so I will guess that socket.io isn't even listening on any port.
You're getting that error, because http://localhost:3000/socket.io/socket.io.js is being served by express and of course you don't have that route setup (And you shouldn't do it).
The fix is to attach the express server to socket.io
index.js
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server); // Pass server to it instead of port
// Now you can pass `io` to any file you want, and setup your socket logic
// Do the same for express app.
// Or handle the logic here, whatever you prefer
server.listen(3000); // Listen
You can do that, or use a different port for socket.io.
Could you further explain or point me to documentaion about how
socket.io works, why it can not run on same port as my node app
You can't have to applications, or server listening on the same port, otherwise you will get: Error: listen EADDRINUSE
That's why if you wish to use express & socket.io on the same port, you have to use the same server listening on that specific port for both.
I was having this same issue and followed these steps sugested by #Marcos but it didn't work in my case, so I removed all the socket.io, socketio and express packages I had, reinstalled as the following
npm i express --save
npm i socket.io#2.4.1 --save
and made sure they were updated, as before Ubunto was downloading the 2.1 ver of socket.io and it had a few vulnerability issues, then instead of using the 'require' format I used 'import' as follows
import express from 'express';
import http from 'http';
import createGame from './public/game.js';
import socketio from 'socket.io';
const app = express();
const server = http.createServer(app);
const sockets = socketio(server);
and it finally worked. After struggling with this all day I thought this would be helpfull if someone have a similar issue in the future.
I am using node.js to run locally (To start the server I am using: "node index.js" in my terminal) and I keep getting this error when I try to link my array.js file.
GET http://localhost:3000/array.js 404 (Not Found)
My file paths are as such if that matters...
/Campus/views(Index.pug file)
/Campus(Index.js file)
/Campus/public/js(array.js file)
My HTML(pug syntax) Header:
doctype html
head
script(src='array.js', type='text/javascript')
link(rel='stylesheet', type='text/css', href='http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css')
link(rel='stylesheet', type='text/css', href='http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css')
I feel that I did indeed reference my .js file correctly here, but this is my first time using node.js and maybe there is something I am over looking.
My Index.js code:
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 3000));
app.use(express.static(__dirname + '/public'));
// views is directory for all template files
app.set('views', 'views');
app.set('view engine', 'pug');
app.get('/', function(request, response) {
response.render('index', {
title: 'Homepage'
});
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
You put it in public/js/array.js, but you're referencing it in public/array.js. Your path should be js/array.js
Documentation: https://expressjs.com/en/starter/static-files.html
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.
I am trying out doT.js for the first time and have written a very basic server setup:
'use strict';
var express = require('express');
var app = express();
var doT = require('express-dot');
var pub = __dirname+'/public';
var vws = __dirname+'/views';
app.set('views', vws);
app.set('view engine', 'dot');
app.engine('html', doT.__express);
app.use('/css',express.static(pub + '/css'));
app.use('/img',express.static(pub + '/imgs'));
app.use('/js',express.static(pub + '/js'));
app.get('/', function(req, res){
res.render(vws + '/index.html', { title: 'dynamic title' });
});
app.listen(8080);
console.log('Server running on port 8080');
When I run the server and goto myaddress:8080 I get the following error:
Error: ENOENT, open '/home/myproject/views/layout.html'
If I try calling index.html with res.sendFile it works (although of course I can't pass variables that way)
res.sendFile(vws + '/index.html')
Where am I going wrong?
Why am i getting an error which seems to relate to a failed attempt at opening "layout.html" when no example I have seen mentions such a file?
I need to use res.render in order to pass variables to the template, but all the examples I have found do it the same way I tried in my first attempt.
dot.js isn't yet integrated with express 4.0's view engine middleware hook.
Swig is a similar application that is. It isn't quite as fast as dot.js, but for me it has a great balance of speed and features with an extremely intuitive syntax.
Full disclosure: I like swig.
I have started a node js project and up to now I have included my html pages/css/etc in a folder named 'html'. I have npm- installed the relevat modules also. But some error message is displayed during the launch. plz help me out.Thnx
Project Hierarchy
squadra-server.njs
var express = require('express');
var app = express.createServer();
app.get('/', function(req, res){
res.send('Hello World');
});
app.configure(function () {
app.use(express.static(__dirname + '/html'));
})
app.listen(8000);
error msg
You have to configure the path to node.exe in your run configuration. Should not be much of a problem...