I am trying to get node.js to run on Amazon AWS
var http = require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write("<!DOCTYPE \"html\">");
response.write("<html>");
response.write("<head>");
response.write("<title>Hello World Page</title>");
response.write("</head>");
response.write("<body>");
response.write("Hello World!");
response.write("</body>");
response.write("</html>");
response.end();
});
server.listen(8080);
console.log("Server is listening");
I created the following Security groups
Inbound:
Port Range: 8080, Destination: 0.0.0.0/0
Outbound:
Port Range: 8080, Destination: 0.0.0.0/0
Node v4.4.1 is installed
Request, Express, and Socket.io are also installed
The script runs on the server without errors but it is not visible from the web?
You need to specify port 8080 explicitly in the browser. Try 54.213.188.86:8080 when the server is running.
Related
I have executed a nodejs server on port 8080 on cPanel using SSH access.
I have provided public IP address of my server as a host name for node js server.
But still I m not able to access the server by entering the public IP address and port number in browser URL.
Code:
'use strict';
const Hapi = require('hapi');
const server = Hapi.server({
port: 8080,
host: '1.1.1.1' //servers public IP adrress
});
server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
return 'Hello, world!';
}
});
const init = async () => {
await server.start();
console.log(`Server running at: ${server.info.uri}`);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
I have solved this problem.
The problem was the port on which I was trying to run this application was not open to outside accessors.
I contacted to support team of cloud server on which I have deployed my application, and then they have opened the port.
And after opening the port now it is accessible to outside accessors.
Thank you for your time and efforts.
I've two node.js servers: one is http, and the other is https
//HTTP server
http.createServer(function(request,response){
unifiedServer(request,response);
}).listen(config.httpPort,function(){
console.log('listening at port ' + config.httpPort)
});
//HTTPS server
var httpsServerOptions = {
'key': fs.readFileSync('./https/key.pem'),
'cert': fs.readFileSync('./https/cert.pem')
};
https.createServer(httpsServerOptions,function(request,response){
unifiedServer(request,response);
}).listen(config.httpsPort,function(){
console.log('listening at port ' + config.httpsPort)
});
//Instantiating the servers
var unifiedServer = function(request,response){....
When I run it, it will console.log listening at port 3000 (http) and listening at port 3001 (https)
3000 works just fine but.. When going into 3001 I get This page isn’t working
I've checked in case the key and certifications might be the problem, but as far as I can see they are doing their work just fine.
Any insights into this problem are appreciated
You need https on the URL to the 3001 server:
https://localhost:3001/home
I am working on setting up an aws instance to listen for http POST's. When running the server and client both as local host, everything seems to work fine. However, when running trying to make a post with the client to an aws instance with the server running, I am getting a connect ECONNREFUSED error.
The aws instance (ubuntu server) that I am using has both ports 80 and 8080 open to all ip addresses. I am using the pm2 module to keep the server running. Although using pm2 is giving the same error.
Server Setup: (aws instance terminal)
$ sudo apt-get install git
$ curl -sL https://deb.nodesource.com/setup | sudo bash -
$ sudo apt-get install -y nodejs
$ sudo npm install pm2 -g --unsafe-perm
Using node to start server:
$ node nodeServerTest.js
Using pm2 to start server:
$ pm2 start nodeServerTest.js --name "nodeServerTest" -i max
Server Code:
// nodeServerTest.js
var http = require("http");
function startServer(port, ip) {
// requestListener handles incoming requests
function requestListener(request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// destroys connection if too long
if (body.length > 1e6) {
request.connection.destroy();
}
});
request.on('end', function() {
// checks for json, otherwise destroys connection
try {
var POST = JSON.parse(body);
console.log('valid post:')
console.log(POST)
response.end('post accepted');
}
catch(err) {
console.log('bad post, ending connection')
response.connection.destroy();
}
});
}
else {
response.end();
}
};
// creates the eventEmitter
var server = http.createServer(requestListener);
// beigns listening on specified port
server.listen(port, ip);
// logs when someone attempts to connect
server.on('connection', function (stream) {
console.log('someone connected!');
});
// notifies when server has started
console.log('Server running at http://'+ip+':'+port);
}
startServer(8080, '127.0.0.1');
Client Code: (I change the host field to the ip address when attempting to post to the aws instance)
// nodeClientTest.js
function httpPost() {
var http = require("http");
var postData = JSON.stringify({
'msg': 'Hello World!'
});
var options = {
host: "localhost", // using correct public ip
port: 8080,
method: 'POST',
path: '/',
headers: {
'Content-Type': 'application/json',
'Content-Length': postData.length
}
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(postData);
req.end();
}
httpPost();
Thank you for any help, if more information is needed please leave a comment
You are binding your server to the loopback interface here:
startServer(8080, '127.0.0.1');
..which makes is available only locally. To allow access via your eth0 interface, so from other network hosts replace this line with:
startServer(8080);
..to listen on port 8080 TCP on all interfaces, according to Node.js manual.
PS Please remember that your private IP on AWS EC2 != public IP address. You can check both by running ec2metadata command on your EC2 host.
An explanation, as OP requested:
each TCP server socket has to be bound to a specific network interface. This is because you make you connect your client TCP socket to a combination of IP:port and the IP is bound to the interface.
loopback interface with a 127.0.0.1 IP address is as special virtual interface available only from the localhost, targeting ifself (hence the name),
So when you run your server binding it to loopback the only way you could have only made the request to it would be initiating the connection from that host itself, for example with telnet like this: telnet 127.0.0.1 8080.
You could have bind the server to the actual IP of eth0 interface but this is inpractical, especially on EC2 servers where private IPs change.
That's why I proposed the simpler, universal syntax. A side effect is that this way your server listens on both loopback and eth0 but it only helps, for example when you want to separate your own, local traffic from the rest of the traffic by based on the interface used.
It seems like your server is only binding to the local address of the server (127.0.0.1) and not listening to connections outside of the server.
Please try to change the listening address of the server to 0.0.0.0
startServer(8080, '0.0.0.0');
I would also advise you to check the express web framework for your server.
These are the versions of node and required modules I am using:
Node.js: 0.10.16
Websocket Library: einaros/ws ws#0.4.28
Proxy server: nodejitsu/node-http-proxy http-proxy#0.10.3
When I run the following program my console output looks like this, and doesn't move beyond this point:
$ node app.js
proxy: got upgrade, proxying web request
wss: got connection
Here's the code:
// app.js
// A simple proxying example
//
// Setup websocket server on port 19000
// Setup proxy on port 9000 to proxy to 19000
// Make a websocket request to 9000
//
var WebSocket = require('ws'),
WebSocketServer = WebSocket.Server,
proxy = require('http-proxy');
// goes in a loop sending messages to the server as soon as
// the servers are setup
var triggerClient = function() {
var ws = new WebSocket('ws://localhost:9090/');
ws.on('open', function() {
console.log('ws: connection open');
setInterval(function() {
ws.send("Hello");
}, 1000);
});
ws.on('message', function(data) {
console.log('ws: got ' + data);
});
}
// setup websocket server and a proxy
//
var go = function() {
// setup a websocket server on port 19000
//
var wss = new WebSocketServer({ port: 19000 });
wss.on('connection', function(ws) {
console.log('wss: got connection');
ws.on('message', function(data) {
console.log('wss: got ' + data);
ws.send('wss response: ' + data);
});
});
// setup a proxy server
var server = proxy.createServer(function (req, res, proxy) {
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 19000
});
});
server.on('upgrade', function (req, socket, head) {
console.log('proxy: got upgrade, proxying web request');
server.proxy.proxyWebSocketRequest(req, socket, head, {
host: 'localhost',
port: 19000
});
});
server.listen(9090, triggerClient);
};
process.nextTick(go);
My problem eventually started when I was trying to use hipache, I then simplified things to node-http-proxy and then finally to this piece of code.
If you change the port the WebSocket client is connecting to from 9090 to 19000 (thereby bypassing the proxy), things seem to work fine.
Any suggestions, pointers, feedback would be greatly appreciated.
Thanks!
The core problem is that the master branch of node-http-proxy is only compatible with node <= 0.8.x (see https://github.com/nodejitsu/node-http-proxy#when-to-use-node-http-proxy): there's a tree that implements support for 0.10.x (see https://github.com/nodejitsu/node-http-proxy/tree/caronte) but it isn't the mainline branch and I haven't found any indication of when it will be merged in and available.
I just installed node.js on Windows. I have this simple code which does not run:
I get:
Error: listen EADDRINUSE
Is there a config file that tells node.js to listen on a specific port?
The problem is I have Apache listening on port 80 already.
EDIT:
var http = require('http');
var url = require('url');
http.createServer(function (req, res) {
console.log("Request: " + req.method + " to " + req.url);
res.writeHead(200, "OK");
res.write("<h1>Hello</h1>Node.js is working");
res.end();
}).listen(5454);
console.log("Ready on port 5454");
There is no config file unless you create one yourself. However, the port is a parameter of the listen() function. For example, to listen on port 8124:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
If you're having problems finding a port that's open, you can go to the command line and type:
netstat -ano
To see a list of all ports in use per adapter.
I usually manually set the port that I am listening on in the app.js file (assuming you are using express.js
var server = app.listen(8080, function() {
console.log('Ready on port %d', server.address().port);
});
This will log Ready on port 8080 to your console.
you can get the nodejs configuration from http://nodejs.org/
The important thing you need to keep in your mind is about its configuration in file app.js which consists of port number host and other settings these are settings working for me
backendSettings = {
"scheme":"https / http ",
"host":"Your website url",
"port":49165, //port number
'sslKeyPath': 'Path for key',
'sslCertPath': 'path for SSL certificate',
'sslCAPath': '',
"resource":"/socket.io",
"baseAuthPath": '/nodejs/',
"publishUrl":"publish",
"serviceKey":"",
"backend":{
"port":443,
"scheme": 'https / http', //whatever is your website scheme
"host":"host name",
"messagePath":"/nodejs/message/"},
"clientsCanWriteToChannels":false,
"clientsCanWriteToClients":false,
"extensions":"",
"debug":false,
"addUserToChannelUrl": 'user/channel/add/:channel/:uid',
"publishMessageToContentChannelUrl": 'content/token/message',
"transports":["websocket",
"flashsocket",
"htmlfile",
"xhr-polling",
"jsonp-polling"],
"jsMinification":true,
"jsEtag":true,
"logLevel":1};
In this if you are getting "Error: listen EADDRINUSE" then please change the port number i.e, here I am using "49165" so you can use other port such as 49170 or some other port.
For this you can refer to the following article
http://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-shared-hosting-accounts