Http-server nodejs running but not working - node.js

I am trying to run http-server for nodejs.
After using npm start the server starts on the given port(8000) perfectly with a few ignorable errors. But when I try to run the application url, it says 'Webpage is not available'.
When i tried to ping the IP it responds by sending packets perfectly.
When I run http-server command it shows that it is running on 127.0.0.1:8080 and 172.31.46.121:8080. I tried changing the localhost port to 8080,but with no difference in results.
I am using putty client to run linux on windows.
nodejs version-5.4.1
npm version-3.7.0
Please help..
There is one more thing..
I ran this server on putty at port 80. Then with the server still running i tried to run the same nodejs server using Bitnami client(i.e. using npm start) at the same port(80) and there was no conflict of ports. Even the app is running fine at that port when I run it through Bitnami client.
http-server file code-
` #!/usr/bin/env node
var colors = require('colors'),
httpServer = require('../lib/http-server'),
argv = require('optimist').argv,
portfinder = require('portfinder'),
opener = require('opener');
if (argv.h || argv.help) {
console.log([
"usage: http-server [path] [options]",
"",
"options:",
" -p Port to use [8080]",
" -a Address to use [0.0.0.0]",
" -d Show directory listings [true]",
" -i Display autoIndex [true]",
" -e --ext Default file extension if none supplied [none]",
" -s --silent Suppress log messages from output",
" --cors Enable CORS via the 'Access-Control-Allow-Origin' header",
" -o Open browser window after staring the server",
" -c Set cache time (in seconds). e.g. -c10 for 10 seconds.",
" To disable caching, use -c-1.",
" -h --help Print this list and exit."
].join('\n'));
process.exit();
}
var port = argv.p || parseInt(process.env.PORT, 10),
host = argv.a || '0.0.0.0',
log = (argv.s || argv.silent) ? (function () {}) : console.log,
requestLogger;
if (!argv.s && !argv.silent) {
requestLogger = function(req) {
log('[%s] "%s %s" "%s"', (new Date).toUTCString(), req.method.cyan, req.url.cyan, req.headers['user-agent']);
}
}
if (!port) {
portfinder.basePort = 8080;
portfinder.getPort(function (err, port) {
if (err) throw err;
listen(port);
});
} else {
listen(port);
}
function listen(port) {
var options = {
root: argv._[0],
cache: argv.c,
showDir: argv.d,
autoIndex: argv.i,
ext: argv.e || argv.ext,
logFn: requestLogger
};
if (argv.cors) {
options.headers = { 'Access-Control-Allow-Origin': '*' };
}
var server = httpServer.createServer(options);
server.listen(port, host, function() {
log('Starting up http-server, serving '.yellow
+ server.root.cyan
+ ' on port: '.yellow
+ port.toString().cyan);
log('Hit CTRL-C to stop the server');
if (argv.o) {
opener('http://127.0.0.1:' + port.toString());
}
});
}
if (process.platform !== 'win32') {
//
// Signal handlers don't work on Windows.
//
process.on('SIGINT', function () {
log('http-server stopped.'.red);
process.exit();
});
}
`

Please provide some code,
out of pure speculation there may be an issue with bind IP ie. you may have your IP address of server bind to 127.0.0.1 which can only be accessed from locahost, change it to 0.0.0.0 to allow access from outside.
var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {
'content-type': 'text/plain'
});
res.end('It works');
}).listen(3000, '0.0.0.0');

Related

Docker network setting for recieve Syslog message from Network device

I use node.js module name simple-syslog-server to listen port 514, It work correctly in my computer
this is my code.
//syslog-config
import Syslog from 'simple-syslog-server';
// Create our syslog server with the given transport
const options = { type: 'udp4' };
const address = myip; // My ip
const port = 514;
const listen = { host: address, port: port };
var syslogserver = Syslog.UDP(options);
var syslogsubscribelist = [];
//syslog listener
syslogserver.on('msg', data => {
console.log(data);
})
.listen(listen)
.then(() => {
console.log(`Now listening on: ${address}:${port}`);
});
when I compile container with this setting.
docker run -p 514:514/udp -d patom2000/webex-bot
Program didn't receive syslog packet.What should I do with docker network setting?

Unable to run nodejs script for a json rpc test case automation

I am trying to run a nodejs script written for a json rpc test case automation. However, I keep getting the error:
npm run test\resources\nv-jsonrpc-tests\pingServer.spec.js
error missing script: test\resources\nv-jsonrpc-tests\pingServer.spec.js
verbose exit [ 1, true ]/>
var rpc = require('node-json-rpc');
var options = {
// int port of rpc server
port: 8080,
// string domain name or ip of rpc server, default '127.0.0.1'
host: '127.0.0.1',
// string with default path, default '/'
path: 'https://',
// boolean false to turn rpc checks off, default true
strict: true
};
// Create a server object with options
var client = new rpc.Client(options);
client.call(
{"jsonrpc": "2.0", "method": "Ping", "params": {classname: 'NServer'},
"id": 1},
function (err, res) {
// Check whether it worked and capture the response and error
if (err) { console.log(err); }
else { console.log(res); }
}
);
Expectation:
Client send request with 'Ping' and receives 'Pong' from the server response.
You seems to confuse npm run and node
npm run is meant to execute scripts declared in your package.json
node can directly execute the script in the file you give
Running this should work
node test\resources\nv-jsonrpc-tests\pingServer.spec.js

Events gulp-nodemon are not firing

I am currently trying to write a gulp task that allows me to serve development code up through a node webserver and use browser sync to reload the page. In doing so i'm attempting to use the events with nodemon, so for example when start event occurs, I want my gulp to log what its starting. Currently the events for gulp nodemon are not firing at all. No error is being thrown and the web server is starting. I'm not sure what I am doing wrong.
gulp.task('serve-dev', ['inject'], function(){
var isDev = true;
var nodeOptions = {
script: config.nodeServer,
delayTime: 1,
env: {
'PORT': port,
'NODE_ENV': isDev ? 'dev': 'build'
},
watch: ['server.js']
};
$.nodemon(nodeOptions)
.on('start', function(){
log('*** nodemon started');
// startBroswerSync();
})
.on('restart', function (ev){
log('*** nodemon restarted');
log('files changed on restart:\n' + ev);
})
.on('crash', function(){
log('Server Crashed for some reason');
})
.on('exit', function(){
log('Server Ended Cleanly');
})
Here is my config File:
module.exports = function() {
var client = './src/';
var temp = './.tmp/';
var server = './server.js';
var config = {
// Location of index.html
index: client + 'index.html',
// Temp folder
temp: temp,
// All of the js files to load
js: [
client + '**/*.module.js',
client + '**/*.js',
'!' + client + '**/*.spec.js'
],
// Root Folder of App(Where to find index.html etc...)
client: client,
// Where to find build Sass and CSS files
css: [temp + '*css', client + 'css/*.css'],
// All Js to Vet
alljs: [
'./src/**/*.js',
'./*js'
],
// Path to Node Server
server: server,
//Sass to Compile
sass: ['src/scss/*.scss'],
// Bower and NPM Locations
bower: {
json: require('./bower.json'),
directory: './bower_components/',
ignorePath: '../..'
},
// Node Settings
defaultPort: 7203,
nodeServer: './server.js'
};
config.getWiredepDefaultOptions = function() {
var options = {
bowerJson: config.bower.json,
directory: config.bower.directory,
ignorePath: config.bower.ignorePath
};
return options;
};
return config;
};
Completely Unrelated answer, log method was not functioning properly, thus no log statements....sorry

Connection error when deploying with flightplan

I am running this code with flightplan:
var plan = require('flightplan');
var appName = 'personal-website';
var username = 'deploy';
var startFile = 'bin/www';
var tmpDir = appName+'-' + new Date().getTime();
// configuration
plan.target('staging', [
{
host: '104.131.153.117',
username: username,
}
]);
plan.target('production', [
{
host: '104.131.153.117',
username: username,
},
//add in another server if you have more than one
// {
// host: '104.131.93.216',
// username: username,
// agent: process.env.SSH_AUTH_SOCK
// }
]);
// run commands on localhost
plan.local(function(local) {
local.log('Copy files to remote hosts');
var filesToCopy = local.exec('git ls-files', {silent: true});
// rsync files to all the destination's hosts
local.transfer(filesToCopy, '/tmp/' + tmpDir);
});
// run commands on remote hosts (destinations)
plan.remote(function(remote) {
remote.log('Move folder to root');
remote.sudo('cp -R /tmp/' + tmpDir + ' ~', {user: username});
remote.rm('-rf /tmp/' + tmpDir);
remote.log('Install dependencies');
remote.sudo('npm --production --prefix ~/' + tmpDir + ' install ~/' + tmpDir, {user: username});
remote.log('Reload application');
remote.sudo('ln -snf ~/' + tmpDir + ' ~/'+appName, {user: username});
remote.exec('forever stop ~/'+appName+'/'+startFile, {failsafe: true});
remote.exec('forever start ~/'+appName+'/'+startFile);
});
This is the error I get when I try to deploy:
Error connecting to 104.131.153.117: Error: Authentication failure. Available authentication methods: publickey,password
I have no idea what going on. I am trying to deploy this to digital ocean. I am not sure what is causing this problem.
It looks like you haven't authenticated to your remote host properly. You need to add your SSH key to the remote host for password-free access.
The command to do this is
$ ssh-copy-id <user>#<host>
If you need to specify an exact key to use, use the following command
$ ssh-copy-id -i <path-to-.pub-file> <user>#<host>

How to get the exact IP address of the Restify server on listen?

Consider the following code for rest API node server.
var restify = require('restify');
var server = restify.createServer();
server.get('/echo/:name', function (req, res, next) {
res.send({name: req.params.name});
next();
});
server.listen(8080, function () {
console.log('%s listening at %s', server.name, server.url);
});
Running up that server with node:
$ node echo.js
restify listening at http://0.0.0.0:8080
It shows 0.0.0.0 which is wrong.
Can anyone the me how to console log the exact IP of the server when its turned on?
Thanks
Update:
On executing the following code I am getting the below mentioned output, which is again makes difficult, which IP to pick?
rest_server.listen(config.appPort, function () {
var adrs = require('os').networkInterfaces();
console.log(adrs);
console.log('%s listening at %s', rest_server.name, rest_server.url);
});
Output:
{ 'Local Area Connection': [ { address: '192.168.3.60', family: 'IPv4', internal
: false } ],
'Loopback Pseudo-Interface 1':
[ { address: '::1', family: 'IPv6', internal: true },
{ address: '127.0.0.1', family: 'IPv4', internal: true } ],
'isatap.TEST.ORG':
[ { address: 'fe80::5efe:c0a8:33c',
family: 'IPv6',
internal: false } ] }
restify listening at http://0.0.0.0:8080
You can set the real address to the listen method, see
http://mcavage.github.io/node-restify/#Server-API and http://nodejs.org/docs/latest/api/net.html#net_server_listen_path_callback
server.address() may return the address the server was bound to:
http://nodejs.org/docs/latest/api/net.html#net_server_address
Had the Same issue and figured out the problem, basically you can pass another parameter to the .listen() function and that should be your server IP address
server.listen(port, [host], [backlog], [callback])
server.listen(port, YOUR IP ADDRESS, function(){ });
for you to get your server ip address just do "traceroute www.WEBSITE_URL.com" in the terminal.
let me know if you still have an issue.
thanks
Mahdi
Got some solution, which is as follows.
Any improvements on the same is always welcomed.
var osDetails = require('os');
function getDynamicIP(calbck) {
var ip;
try {
var adrs = osDetails.networkInterfaces();
for (key in adrs) {
if (adrs.hasOwnProperty(key)) {
if (adrs[key][0].internal === false && adrs[key][0].family === 'IPv4') {
ip = adrs[key][0].address;
break;
}
}
}
}
catch (e) {
return calbck(e, null);
}
return calbck(null, ip);
}

Resources