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
Related
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 have a node server with express on top. Godaddy is the domain registrar that I use.
If I try to connect with www.example.com doesn't work, only with https://www.example.com.
This is how the code looks like:
app.use(express_enforces_ssl());
app.enable('trust proxy');
app.use (function (req, res, next) {
if(req.secure){
next();
}else {
res.redirect('https://' + req.headers.host + req.url);
}
});
var options = {
ca: fs.readFileSync('./gd_bundle-g2-g1.crt'),
key: fs.readFileSync('./server_cert_key.key'),
cert: fs.readFileSync('./cfbe0f99da37dcae.crt')
};
https = require('https').createServer(options, app);
io = require('socket.io')(https);
However, if I 'ping www.example.com' the server is reached, but not in the browser.
The process is running on port 443 (dedicated port for secured connection).
I have made port forwarding from internal port 443 with output on port 80, this is how domain registrar works, only with port 80.
I don't know how can I fix it. Do you have any idea ?
DNS doesn't usually require ports info. Browser automatically assumes 80 for http scheme and 443 for https scheme.
The app code is only listening on 443. You need to add additional:
require('http').createServer(app).listen(80);
Try normalizing the port before listen to it.
In the code below, the port will be normalized according to the app settings. If none were found, it will be defaulted to port 80
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) return val;
if (port >= 0) return port;
return false;
}
//port 443 if https:// is detected
var port = normalizePort(process.env.PORT || '80');
// for me, I imported ('http') instead of ('https')
// but it also works on port 443
https.listen(port, function listening() {
console.log('Listening on %d', server.address().port);
});
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.
I'm trying to run a basic node.js file on an aws server running ubuntu 14.04 and apache 2.4.7
var http = require('http');
var hostname = '33.33.33.33';
var port = 3000;
var server = http.createServer(function(req, res) {
console.log(req.headers);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello World</h1>');
});
server.listen(port, hostname, function() {
console.log('Server running at http://${hostname}:${port}/');
});
The hostname is just the IP to the server. Should it be something else? Should the hostname be the IP or should it be something else?
The above code gives the following error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRNOTAVAIL
at errnoException (net.js:901:11)
at Server._listen2 (net.js:1020:19)
at listen (net.js:1061:10)
at net.js:1135:9
at dns.js:72:18
at process._tickCallback (node.js:415:13)
at Function.Module.runMain (module.js:499:11)
at startup (node.js:119:16)
at node.js:901:3
********Update*********
I have updated my code with localhost. That got rid of the error and allowed me to run the .js file. However I can't access the file from the server. I type in the IP like so
**.**.**.**:3000
This returns the message:
This site can’t be reached
**.**.**.** refused to connect.
ERR_CONNECTION_REFUSED
I also try accessing the location the file is located on the server but I get the same result.
**.**.**.**:3000/nodelearning/c1_node_week1/node-express
After I run:
node myNodeApp.js
In the terminal, I just need to access the IP of the server from a web browser right? Do I need to access only the root **.**.**.**:3000 or do I need to access the specific location of the node file **.**.**.**:3000/learningNode/myNodeApp.js
I only need to access the root right?
So **.**.**.**:3000 should work?
Below is the .js file that I'm able to run. But I can't access.
var express = require('express'),
http = require('http');
var hostname = 'localhost';
var port = 3000;
var app = express();
app.use(function (req,res, next) {
console.log(req.headers);
res.writeHead(200, {'Content-Type': 'text/html' });
res.end('<html><body><h1>Hello World</h1></body></html>');
});
var server = http.createServer(app);
server.listen(port, hostname, function(){
console.log('Server running at http:// NVM');
});
Cheers
the issue is with
var hostname = '33.33.33.33';
because when routes are recycled new ip address are assigned to the machine. so this will fail. As a recomendation skip host parameter in listen() or if you still want to use hostname use
var hostname = '127.0.0.1';
or
var hostname = 'localhost';
hope it helps :)
I want to do a simple node.js reverse proxy to host multiple Node.JS applications along with my apache server on the same port 80. So I found this example here
var http = require('http')
, httpProxy = require('http-proxy');
httpProxy.createServer({
hostnameOnly: true,
router: {
'www.my-domain.com': '127.0.0.1:3001',
'www.my-other-domain.de' : '127.0.0.1:3002'
}
}).listen(80);
The problem is that I want to have for example app1.my-domain.com pointing to localhost:3001, app2.my-domain.com pointing to localhost:3002, and all other go to port 3000 for example, where my apache server will be running. I couldn't find anything in the documentation on how to have a "default" route.
Any ideas?
EDIT I want to do that because I have a lot of domains/subdomains handled by my apache server and I don't want to have to modify this routing table each time I have want to add a new subdomain.
For nearly a year, I had successfully used the accepted answer to have a default host, but there's a much simpler way now that node-http-proxy allows for RegEx in the host table.
var httpProxy = require('http-proxy');
var options = {
// this list is processed from top to bottom, so '.*' will go to
// '127.0.0.1:3000' if the Host header hasn't previously matched
router : {
'example.com': '127.0.0.1:3001',
'sample.com': '127.0.0.1:3002',
'^.*\.sample\.com': '127.0.0.1:3002',
'.*': '127.0.0.1:3000'
}
};
// bind to port 80 on the specified IP address
httpProxy.createServer(options).listen(80, '12.23.34.45');
The requires that you do NOT have hostnameOnly set to true, otherwise the RegEx would not be processed.
This isn't baked into node-http-proxy, but it's simple to code:
var httpProxy = require('http-proxy'),
http = require('http'),
addresses;
// routing hash
addresses = {
'localhost:8000': {
host: 'localhost',
port: 8081
},
'local.dev:8000': {
host: 'localhost',
port: 8082
},
'default': {
host: 'xkcd.com',
port: 80
}
};
// create servers on localhost on ports specified by param
function createLocalServer(ports) {
ports.forEach(function(port) {
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello from ' + port + '</h1');
}).listen(port);
});
console.log('Servers up on ports ' + ports.join(',') + '.');
}
createLocalServer([8081, 8082]);
console.log('======================================\nRouting table:\n---');
Object.keys(addresses).forEach(function(from) {
console.log(from + ' ==> ' + addresses[from].host + ':' + addresses[from].port);
});
httpProxy.createServer(function (req, res, proxy) {
var target;
// if the host is defined in the routing hash proxy to it
// else proxy to default host
target = (addresses[req.headers.host]) ? addresses[req.headers.host] : addresses.default;
proxy.proxyRequest(req, res, target);
}).listen(8000);
If you visit localhost on port 8000 it will proxy to localhost port 8081.
If you visit 127.0.0.1 on port 8000 (which is not defined in our routing hash) it will go to the default 'location', namely xkcd.com on port 80.