Linux nodejs rest service work only localhost - node.js

i'm developing a REST API with node js on linux.
This my first sample code to try if all works fine:
'use strict';
var express = require("express");
var app = express();
var port = process.env.PORT || 8080 ;
app.listen(port, "127.0.0.1", function(){
console.log("Express server is listening on port ", port);
});
i have try to call localhost:8080 into linux server and works fine.
If i try to call trhe IP of server with this port by a external IP the express server not responding.
Any help about this?
Thanks

Your second parameter to the app.listen() api, which you set to "127.0.0.1" is the hostname. This will cause node to only listen for requests matching that host name from the request domain.
This is an optional parameter.
Perhaps try the app.listen(port, callback) form of the api?
app.listen(port, function () {
console.log("Express server is listening on port ", port);
});
app.get('/', function (req, res) {
res.send('Hello world!')
});
Or you can move the [hostname] parameter to a configuration file if you don't want your service to listen to every host name.
See the server.listen() documentation for better insight into parameter default behaviour.

Try this so your app listens on all network interfaces and not only on localhost:
app.listen(port, "0.0.0.0", function(){
console.log("Express server is listening on port ", port);
});

Related

This site can’t be reached aws

I am trying to deploy node.js on AWS ec2
I followed this tutorial and that my code
const express = require('express') ;
const app = express();
const port = process.env.PORT || 3000 ;
app.get('/', (req , res) =>{
res.send('Connected');
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
and when I start it gives me the
Example app listening at http://localhost:3000
but when I try to reach it from the browser I can't reach it
any idea what can I do or where to look ??
You need to configure inbound and outbound rules in the instance's security group.
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html
I am assuming you have already followed the guide you mentioned and added the necessary security group rules to allow the incoming traffic on port 3000.
Your app should be listening on all the interfaces or on the IP address of your ec2 instance instead of localhost. localhost resolves to 127.0.0.1 which is a loopback interface that is not accessible over the internet.
documentation
[app.listen([port[, host[, backlog]]][, callback])]
const express = require('express') ;
const app = express();
const port = process.env.PORT || 3000 ;
app.get('/', (req , res) =>{
res.send('Connected');
});
app.listen(port, '0.0.0.0',() => {
console.log(`Example app listening at http://localhost:${port}`);
});

How to run NodeJs SocketIO on server (Centos 7)

I create app with nodejs socket io. It works clearly at localhost (port: 3000). But when i deploy it to my server in there i can run my app on 3000 port but client side throw timeout. How can i solve it?
var fs = require('fs');
var https = require('https');
var options = {
key: fs.readFileSync('ssl.my-key.key'),
cert: fs.readFileSync('ssl.my-cert.crt')
};
var server = https.createServer(options);
var io = require('socket.io').listen(server);
var port = 3000;
const database = require('./Database');
io.on('connection', (socket) => {
socket.on('message', async (msg) => {
// I do some action here.
});
socket.on('disconnect', (msg) => {
// some action in here too
});
});
server.listen(port, () => {
console.log('listening on *:' + port);
});
It seems like your issue is with port forwarding.
In order for your server to be publicly accessed, it needs to have all ports forwarded appropriately. Locally and on the router.
Check this link to learn more about how to port forward on linux: https://linuxacademy.com/guide/11630-internal-port-forwarding-on-linux-using-the-firewall/
And this to learn more about router port forwarding, but this will really depend on your router.
https://www.noip.com/support/knowledgebase/general-port-forwarding-guide/
However, I don't recommend you to take care of hosting on your own machine(s). I
suggest you use Heroku, you can op in for their free servers, you don't need to pay.
More about heroku and NodeJS: https://linuxacademy.com/guide/11630-internal-port-forwarding-on-linux-using-the-firewall/
let we debug your node js app.
1) add some logs on database connection, http.createserver, also where you have to check if not success then catch exception
2) you should have to open port on centOs before start your node js app
3) you should have test you with domain name or ip address
as per you comment you got connection timeout , you mean node js server trying to connect with port 3000 but node not able to connect and its throws error with connection timeout
also send your sample code of your main index file so we can investigate your problen
thanks.

Node.js express ERR_CONNECTION_REFUSED in VMware

I have set up vmware workstation, Ubuntu 16.06 desktop as my guest machines, windows 10 as host.
nodejs 9.4.0
express 4.16.2
and simple server HTTP and express:
const http = require('http'),
PORT = 4000;
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('It works!');
res.end();
}).listen(PORT);
console.log("Listening on port " + PORT);
**/
/*** EXPRESS BASED TEST*/
const express = require('express');
const app = express();
PORT = 4000;
app.get('/', (req, res)=>{
res.send("it works!");
})
app.listen(PORT, 'localhost', ()=>{
console.log('Listening on port: ' + PORT)
});
/****/
What happens is, when I try to open test webpage from my host browser when guest runnin express - I get ERR_CONNECTION_REFUSED. BUT when i start simple http server - it connects! I tried to connect with telnet, ssh... turn of firewall... behavior is the same...
Is it something wrong with express? Is there a way to fix it?
The solutions is here:
Node.js connect only works on localhost
In my express app I make it listen on localhost, which is 127.0.0.1 and which is loopback address. After changing it to 0.0.0.0 the problem was solved.

Possible to run socket.io server.js file automatically?

I make chat messaging but I need to start server daily for that there is any possibility to start the server automatically in AWS or any other ways.
// Setup basic express server
var io = require('../..')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});

Can't access nodejs server on aws

I have an AWS EC2 instance which I am using for my node js application. I cannot access any application page on the server.
I wrote this simple code solely for testing purposes but I cannot access even this from my browser.
var express = require('express');
var app = express();
app.listen(3000, ()=> {
console.log('listening');
});
app.get('/',(req,res)=> {
res.send('hi');
});
On navigating to http://:3000, I should be able to see "hi" written but the request times out.
Here are my security group configs :
Solved the problem with some help.
Since the port available to me was port 80, so I just forwarded the port 8080 to port 80 via. port forwarding and it worked out.
Sharing the link from where I found the solution:installing nodejs and forwarding port on aws
My code (shown below) is a bit different, but I was having the same problem with connecting from a remote browser:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
What I had to do was replace const hostname with the complete AWS server IP: ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3000/
Make sure you have port 3000 open in your security group, or this will not work.
I was then able to connect to the NodeJS server from my browser on my PC.
Hope this helps. The corrected code is shown below (replace the x's with your actual IP address. You can get this on your EC2 dashboard.
const http = require('http');
const hostname = 'http://ec2-xx-xxx-xxx-xx.compute-1.amazonaws.com/';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
I got the code for this NodeJS server from:
https://websiteforstudents.com/install-the-latest-node-js-and-nmp-packages-on-ubuntu-16-04-18-04-lts/

Resources