I'm learning how to use Node.js apps in a server (not my local machine). In this situation, I'm following this tutorial in order to create a simple web server.
I have installed Node.js, and tested via CLI that it works. I can run javascript code, generate output in the CLI, etc. But I can't manage to make the an app work via URL using a browser.
The app folder structure I have is very simple:
index.js
package.json
package-lock.json
This is the code I'm currently working with in index.js:
var http = require('http'); // 1 - Import Node.js core module
var server = http.createServer(function (req, res) { // 2 - creating server
if (req.url == '/') { //check the URL of the current request
// set response header
res.writeHead(200, { 'Content-Type': 'text/html' });
// set response content
res.write('<html><body><p>This is home Page.</p></body></html>');
res.end();
}
else if (req.url == "/student") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is student Page.</p></body></html>');
res.end();
}
else if (req.url == "/admin") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is admin Page.</p></body></html>');
res.end();
}
else
res.end('Invalid Request!');
});
server.listen(5000); //3 - listen for any incoming requests
console.log('Node.js web server at port 5000 is running..')
If I go via CLI to the app's folder and run the app (node index.js), I can see the expected console.log() output (Node.js web server at port 5000 is running..). But if then I go to the URL pointing at that folder, which I would expect to output <html><body><p>This is home Page.</p></body></html>, it doesn't work (see below for what I get).
I have a domain (http://example.com) with document root in the app's folder. Here's what I have tried:
- https://example.com //browser shows the source code of index.js
- https://example.com:5000 //browser shows ERR_CONNECTION_TIMED_OUT
- https://example.com/:5000 //browser show 404 error
- https://example.com/index.js //browser shows the source code of index.js
- https://example.com/index.js:5000 //browser show 404 error
None of those give the response I would expect. I don't know if this is a problem with my file structure, my server configuration... but I've been looking around and I can't figure why this basic example isn't working in my case, clearly I'm missing something. Any help would be much appreciated!
EDIT: The server where I'm trying to run this app is a LAMP machine with CentOS 7.

index.jsfile then you are running another web server on port 80 but if you are getting theconsole.logline then then on port5000it should work.httpsso you should usehttpand the correct urls areexample.com:5000/notexample.com/:5000