Display text file using node js from a remote server - node.js

Good day! I'm having a hard time fixing this issue. I'm currently using node js webserver (http).
I'm a beginner in using node js so any help would be appreciated.
What I'm hoping to achieve is to display a string 'Hello World!' in the browser while accessing it through the URL. The problem is I'm running the script from a remote server and unfortunately I can't access it through the URL.
The script is running fine but for the browser it returns an error saying:
host didn’t send any data.
ERR_EMPTY_RESPONSE
Here is the script I'm running from the remote server:
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('Hello World!');
response.end();
}).listen(2000);
I think my script doesn't have a problem. So I'm guessing it's from the setup of the server, but I don't have any idea in which part it's causing not to display it. I'm currently using a Linux Server.
Thanks in advance!

From what I can see you are listening on port 2000, are you sure that the url you are requesting the data from also contains the port e.g http://localhost:2000/ ?? Browsers by default tries to connect using port 80 on http and 443 for https, if you are listening on a different port than those, you have to define it in the url, by using a ":" after the domain/ip address
Anyway, have a look at the express module for server side rest APIs, will make request handling so much easier:
const express = require('express');
const app = express().listen(80);
app.get("/",function(request,response){
response.send('Hello World');
});

Express allows you to handle the creation of web servers better.
But node or express, do make sure that the URL you have entered consists of the port number that you have asked the server to listen to.
Another possibility is that the port you have asked to display your response is already being used by another server. You can try using a different port number.
You might have gotten the answer, but this is for the folks out there who are new to node at present and have stumbled upon this stackoverflow question! Good day :)

Related

How to get Node.js http request to work from a browser on Siteground (shared hosting)?

Ok, I've searched around a bunch, and maybe the answer is here and I just couldn't find it because I wasn't using the right search combination or whatever, so please bear with me!
I'm very new to Node and all the tutorials I've read/watched (understandably) use localhost with a port number for examples. I'm having difficulty translating that into a real, shared-server website.
I successfully got Node.js installed on my shared hosting on Siteground (I can check versions, run javascript by pulling up node through putty, etc.).
I can start an http server using port 3000 and my ip address, and I can confirm that the server listener is working using another putty window and curl ipaddressORdomainname: 3000 (for testing purposes until I get it connected). I'm running the following to start the server:
const http = require('http');
const server = http.createServer((req, res) => {
console.log(req.url, req.method);
});
server.listen(3000, 'my_ip_address', () => {
console.log('listening for requests on port 3000')
})
And running curl ipaddressORdomainname: 3000 in another putty window successfully displays / GET in the other putty window with the open port.
What I can't seem to do is use any web browser (tried latest versions of Brave, Chrome, Edge, Firefox, Opera to no avail) to "connect" and show the same result I get from the curl line.
I'm ultimately trying to connect a website to the node.js server, and I think this is my final missing piece I can't seem to find a solution to.
Any guidance would be very appreciated.
Thanks!

App.listen on an already running port of shared hosting

var express = require('express');
var app = express();
app.get("/", function(req,res){
console.log("running on that weird path i made///");
res.send("HELLO THIS IS A WEBPAGE TRYOUT!");
});
app.listen(3000, function(){
console.log("Server running on 3000");
})
I’m trying to create a simple app (for practice) which does a simple hello world. Using express via node.js
I can do it locally no problems.
The problem is I’m trying to run it on an existing server using cPanel shared hosting.
And there is obviously an already running domain name(and has website installed in Wordpress), so I cannot do a simple app.listen to a port which is obviously already running. And I’m guessing therefor I cannot do app.get(“/“....)
I’ve tried a different port-but the get request won’t work(I think obviously since that’s not the one running?)
So when I tell it to listen to the cPanel port, it throws an error that it’s already running.
And I don’t want to stop from the website to run. Is there a way to work this?
Tried also using subdomains. Same result.
Edit:
this worked on postman, when I've sent a get request to that address. tried port 3000, and it showed my res.send on the postman tab.
Edit2:
I've solved this...i forgot to put :3000 on the address..
as in www.example.com:3000
this doesn't work if i don't add the :3000.
and also if i do process.env.PORT and .IP..guessing its because its a shared hosting, or because wordpress is installed...
I won't delete just in case anyone did the same mistake as me.
If the problem that the port is already in use, you may try to use 0 as a port that will cause it to take a random free port on the machine.
const server = app.listen(0, function(){
console.log(`Server is listening on http://localhost:${server.address().port}`);
})

How to run a simple 'Hello World' app on shared hosting with Node.js?

I have been running through some basic tutorials with node.js locally on my desktop and all works fine.
I have been trying to run one of the simple 'Hello World!' apps on my 'live' hosting environment. This is not an active website, just some basic web hosting I use for trying things out. My hosting provider offers a node.js addon for a small amount extra per month which I recently signed up for.
I have amended the code in my file (named app.js) so that it references the host and port provided to me by my hosting provider rather than use localhost as it has been previously. The code looks like:
const http = require('http');
const hostname = '195.62.28.216';
const port = xxxx;
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}/`);
});
With xxxx being substituted for the port allocated to me.
If I kick this off using my SSH client (PuTTY) by running node app.js, I get the message:
Server running at http://195.62.28.216:xxxx/
However, if I visit that URL, I just get a timeout error:
This site can’t be reached
195.62.28.216 took too long to respond.
When I connect to the host using PuTTY, using the username and password my hosting provider gave to me, it appears to default to a folder named /home/my_username. This is the location of my 'Hello World' app file.
I have contacted my hosting provider's support area, but thought I would post here too whilst awaiting a response in case anybody can point me in the right direction of what I may be doing wrong.
Many Thanks, any assistance greatly appreciated.
Thank all above for the quick responses. I think that the problem is that I was going trying to access the 195.62.28.216:xxxx URL directly from my browser but I think it's set up so that this can only be accessed from my actual web hosting environment.
In other words, I added the below to my .htaccess file on my cloud hosting account:
RewriteEngine On
RewriteRule ^ http://195.62.28.216:xxxx/ [P,L]
And when I now go to my website, I get 'Hello World!' as expected. Now I just need to figure out how to make it so that this only happens when I access a specific folder on my website and not the whole thing... :-)

Streaming from NodeJS server not working when access from outside

I have a question about streaming an audio file via a NodeJS server. I'm using the following code:
var http = require('http');
var fs = require('fs');
var filePath = 'media/test.mp3';
var stat = fs.statSync(filePath);
http.createServer(function(request, response) {
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
fs.createReadStream(filePath).pipe(response);
})
.listen(3000);
It does work when I ...
run it locally: http://localhost:3000 or
run it on a different machine in the same network: http://192.168.1.42:3000.
But it does not work when I ...
run it from outside, e.g. calling http://my-public-ip:3000 or
using a DynDNS service: http://my-dyndns-provider.com:3000.
By not working, I mean I can see a pending request ("request is not finished yet!") in Chrome devtools, but the stream sometimes starts only for less than a second, sometimes it doesn't start at all. In the devtools I can see that only 4 KB are loaded (on localhost it's 3.1 MB).
To enable the access from outside, I configured port forwarding on my router, so that requests to port 3000 are forwarded to my computer's internal IP.
For other things than streaming my setup is working, so for example it is possible to call REST routes defined on the server.
EDIT:
Meanwhile, I also tried to do the streaming with PHP instead of NodeJS. But it shows exactly the same behaviour.
Do you guys have an idea what could be the reason?
Thank you!
Looks like some configuration issue with setting up port forwarding in router as you have tried with two different code bases.
If you are doing only for testing you can use localtunnel to expose your localhost to publicly over the internet.
There are few other alternatives also like ngrock or forwardhq.
Hope it helps.
Yesterday, I finally was able to test the exact same setup but with a different router (FritzBox 7320) -- and everything worked as it should. So there must be problems with the router I'm using at home (o2 HomeBox 6441).
I think the best will be trying to get some support in the manufacturer board.
Thanks for your effort anyways!

Trying to run node app on fedora server

Ok I am making website and want to use mongo, express, etc. I setup a server using fedora server ISO. The problem is getting node working. I have followed several tutorials, and its all the same. Nothing works. So I have to be doing something wrong. Trying to get the simplest thing to display on screen.
I think the server is running httpd server, whatever fedora has built in. I get the default fedora server page when going to the url. So the server is running and working, just hasn't been configured. When running node on the server do I have to use httpd-node? Or can it be http, etc.
Here is my app.js
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
And then I have a basic index.html that should be rendered just saying test.
I ssh into the server and run node start, it runs and the console logs the message like it should. But if I go to the address 192.168.1.5, or the domain that points to the server, I get nothing, just a blank page.
If someone can help me get this working, I can actually get to work coding out the application. Any help would be appreciated.
I think you make a confusion. When you build an Express application, you do not need another server at all.
When you start your app with:
app.listen(3000, function () {})
Express returns an http.Server object listening to port 3000.
When you navigate to your local adress on port 3000, you will see your "hello world" message.
It is possible that httpd service is already running in your Fedora environnement on default port 80 (the default port for http, the one your reach when you go to your local adress) but this is an Apache server and you do not need it to run your Nodejs app.
To build a Nodejs server, you can also use httpd-node package, but this is redundant as you're using Express framework.
If you need to serve a simple html file, a method I like for its simplicity is to use ejs template engine, something like this.
res.send('Hello World!') - this is your problem! Why?
How you receive this answer on client side?
Solution: use res.render(..) - for rendering from server or use AJAX on client side for receive this text!
P.S: render page and you don't see blank page anymore! Or use client-server conversation logic with your server through AJAX.
Try 192.168.1.5:3000
If I wrong: show your full project setup...
Test your app with curl (https://curl.haxx.se)! Check connection establishment, and show results here!

Resources