Can't access NodeJS server using express-generator from another computer - javascript

Finally, I have tested my project and I got the problem.
I opened the NodeJS server using ExpressJS. In local, Everything is OK.
But, Another computer can not access my server.
My ip address is '172.30.6.191' and my port is '8080'.
I don't change the express-generator basic code.
Here is WWW.js file code.
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('skeleton1:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '8080');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
How to access this server from another computer.
Help me please.
Thank you.

Make sure that the other computer is also on the same wifi network.

Related

Angular2 + ExpressJs <app-root> dosen't load.

I did read all the other topics but none of the solutions solved my problem.
I write npm start and the server is working as it should but app-root does not it seems like it does not load the client (Angular 2 app).
I just get an empty html page with:
Loading...
(look at my html file down the page)
any idea what can cause it - or any suggested solution ?
Thank you.
app.js
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 mongoose = require('mongoose')
//Set up default mongoose connection
var mongoDB = 'mongodb://localhost/beatblocks';
// Get Mongoose to use the global promise library
mongoose.Promise = global.Promise;
mongoose.connect(mongoDB, function(err) {
if (err){
console.log("error connecting to db...")
}
console.log("connected to database...");
});
// Load Songs Model
require('./models/songs');
const songs = mongoose.model('songs');
// Load Locations Model
require('./models/locations');
const locations = mongoose.model('locations');
// Load users Model
require('./models/users');
const users = mongoose.model('users');
var routeIndex = require('./routes/index');
var routeSongs = require('./routes/songs');
var routeUsers = require('./routes/users');
//var routeLocations = require('./routes/locations');
var app = express();
var router = express.Router();
// Set Static Folder
app.use(express.static(path.join(__dirname, 'views')));
app.use(express.static(path.join(__dirname, '/client/dist')));
app.use(express.static(path.join(__dirname, 'client/src')));
//View Engine
app.engine('ejs', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', routeIndex);
app.use('/songs', routeSongs);
app.use('/users', routeUsers);
//app.use('/locations', routeLocations);
module.exports = app;
www.js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('beatblocksweb:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
app.listen(port, function(){
console.log('Server started on port '+port);
});
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
my index.html :
<html>
<head>
<title>Beat Blocks</title>
</head>
<body>
<app-root>Loading...</app-root>
<app-header></app-header>
</body>
</html>
my project :

reload/reload.js route is not working

reload/reload.js route is not working
I'm using express-generator app code template to create my node applications
I also followed github issues information for this package
https://github.com/alallier/reload/issues/56#issuecomment-288393265
In this comment he said to create a custom route to listen for this file
app.get('/reloader', (req, res) => {
res.type('text/javascript')
res.sendFile(require.resolve('reload/lib/reload-client'))
});
But, when i tried this reload is not working and in console an error exception occurring:
Uncaught DOMException: Failed to construct 'WebSocket': The URL's
scheme must be either 'ws' or 'wss'. 'http' is not allowed.
at new WrappedWebSocket (:164:21)
Here is my code (bin/www)
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var reload = require('reload');
var debug = require('debug')('node1:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
reload(app); // here i'm using reload module
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
I resolved this issue by using reload(app) in ./app.js instead of ./bin/www
It is working fine in app.js file (even if i change the location of this statement) but, in ./bin/www file it is not working.
Code (./app.js):
var express = require('express');
var path = require('path');
var reload = require('reload');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressHandlebars = require('express-handlebars');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
reload(app); // Init Reload module

NodeJs HTTPS connection with express generator

I've created an app using the express generator which all works okay but I now want to run the app with HTTPS, I've tried to configure the node server file in /bin/www to the following:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var debug = require('debug')('****:server');
var https = require('https');
var fs = require('fs');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3001');
app.set('port', port);
var options = {
path: '../app',
port: 443,
key: fs.readFileSync('/var/www/vhosts/keys/wildcard.****.com.key'),
cert: fs.readFileSync('/var/www/vhosts/keys/wildcard.****.com.crt')
}
/**
* Create HTTPS server.
*/
var server = https.createServer(options);
But I can no longer access my app when pointing it to https://
try this out:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
// This line is from the Node.js HTTPS documentation.
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.cert')
};
// Create a service (the app object is just a callback).
var app = express();
// Create an HTTP service.
http.createServer(app).listen(80);
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(443);
and create a self-signed certificate. How ? follow this link http://docs.nodejitsu.com/articles/HTTP/servers/how-to-create-a-HTTPS-server
I solved this issue modifing after creation with express-generator the bin/www file and renamed it as wwws. Then in package.json I change the "source" attribute pointing the new script.
...
"scripts": {
"start": "node ./bin/wwws"
},
...
In wwws I use an https server instead of an http and then I redirect the http requests.
Here my new wwws file. I removed the http lines in the middle of www file and I added the new server section at the end.
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('phishsense:server');
var http = require('http');
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
// Add HTTPS Section
var fs = require('fs');
var https = require('https');
var http_port = normalizePort(process.env.PORT || '8080');
var https_port = process.env.PORT_HTTPS || 8443;
var options = {
key : fs.readFileSync('server.key'),
cert : fs.readFileSync('server.crt')
};
app.set("port",https_port);
/*
° Create HTTPS server.
*/
server = https.createServer(options, app).listen(https_port, function () {
console.log('Magic happens on port ' + https_port);
});
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(https_port);
server.on('error', onError);
server.on('listening', onListening);
// Redirect from http port to https
http.createServer(function (req, res) {
res.writeHead(301, { "Location": "https://" + req.headers['host'].replace(http_port,https_port) + req.url });
console.log("http requet, will go to >> ");
console.log("https://" + req.headers['host'].replace(http_port,https_port) + req.url );
res.end();
}).listen(http_port);
This works for me and lets the structure created by express-generator untouched.

Node.js Processes Don't Detect Port is Already Being Used

I am trying to have two different Node processes (using Cluster) try to become servers to a Port. However, whenever the second process gets to the port, it doesn't detect that the port is being used.
I suspect the reason why they are not detecting if the port is open or not is due to the nature of callbacks (I'm detecting if the port is used or not using the portInUse function, so it is fetched asynchronously, and might cause some type of conflict later on).
Here is the code:
var cluster = require('cluster');
var net = require('net');
var PORT = 1337;
var list = {};
var portIsBeingUsed = false;
// Variable that detects if the port is in use.
var portInUse = function(port, callback) {
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.listen(port, 'localhost');
server.on('error', function (e) {
callback(true);
});
server.on('listening', function (e) {
server.close();
callback(false);
});
};
if (cluster.isMaster) {
for (var i = 0; i < 2; i++) {
cluster.fork();
}
Object.keys(cluster.workers).forEach(function(id) {
console.log("I am running with ID : "+ cluster.workers[id].process.pid);
list[cluster.workers[id].process.pid] = 0;
});
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
} else { // Rest of the logic with all Processes goes here.
// Get the Process ID of the current process in execution.
var pid = cluster.worker.process.pid;
console.log("This is process " + pid + " working now.\n");
// Verify if Port is being used.
portInUse(PORT, function(returnValue) {
if(returnValue) { // Become a Client to the Server
console.log("port " + PORT + " is being used.\n\n");
becomeClient(pid);
} else { // Become a Server
console.log("port" + PORT + " is not being used.\n\n");
becomeServer(pid);
}
});
}
function becomeServer(pid) {
var server = list[pid];
server = net.createServer(function (socket) {
socket.write('Hello Server 1\r\n');
socket.end("hello");
console.log("Someone connected to Server 1. \n");
socket.pipe(socket);
});
server.listen(PORT, function(){
console.log("Process " + pid + " has become the Server on Port " + PORT);
});
server.on("error", function() {
console.log("there was an error on Process " + pid);
console.log("this error was becoming a Server.");
});
}
function becomeClient(pid) {
var client = list[pid];
client = net.connect({port: PORT}, function() {
list[pid].write("I am connected to the port and my pid is " + pid);
});
client.on('data', function(data) {
console.log(data.toString());
list[pid].end();
});
client.on('end', function() {
console.log('disconnected from server');
});
}
And here is the output:
So the first process (In this case Process 9120) becomes the server on port 1337, but then the second process doesn't detect that the port is being used and somehow becomes the server as well (I would expect an EADDRINUSE here, not sure why it isn't showing any errors).
Any help or clarification as to why this isn't working would be greatly appreciated.
Thanks,
This is expected behavior and it is how the cluster module works (by default). It's what allows incoming requests to the same port to be easily distributed among the available workers.
A large part of the point of cluster involves port sharing, so that you can have multiple workers take turns serving requests. The worker processes just request a port from the master, which actually opens the port, and then the master hands requests back to any workers that have requested that port.

OpenShift + Diet.js

Trying to get a simple Diet.js server running on OpenShift (free plan) but the server never starts (runs fine locally). The domain itself (http://twilio-levelout.rhcloud.com/) returns a 503 and the logs throw:
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EACCES
Here's the code:
var server = require('diet'),
app = server();
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
app.get('/', function ($) {
$.end('Hello World!');
});
app.listen("http://" + server_ip_address + ":" + server_port);
The server runs with the default example and a simple Express app but not the above.
Any ideas?
The access error usually means that you are not using the proper port or are trying to bind to interface you have no access to, but when I tried your example, It did not even work on my local machine.
The problem in your example is that app.listen should appear before app.get.
Your example should look like this:
var server = require('diet'),
app = server();
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
app.listen('http://' + server_ip_address + ':' + server_port);
app.get('/', function ($) {
$.end('Hello World!');
});

Categories

Resources