-1

I'm a beginner with Node.js.

I have just installed node JS, and I'm trying to create and execute code through a local server (for practice purposes). But it can't be possible to execute the code using localhost:8080 on a web browser nor through the cmd (I'm on windows 7).

Below you can see what I've been trying so far...

var http = require('http');

http.createServer(function (req, res) { 
   res.writeHead(200, {'Content-Type': 'text/html'});
   res.end('Hello World! i did it');
}).listen(8080);

The browser just says that the site can't be reached and the cmd shows nothing after executing the command. So what would be the problem.

Muath
  • 4,351
  • 12
  • 42
  • 69
  • check this: https://stackoverflow.com/questions/6737824/how-to-run-a-hello-js-file-in-node-js-on-windows – Muath Mar 28 '19 at 18:22
  • try using with another port number – htoniv Mar 28 '19 at 18:24
  • The problem here is probably exterior to your code (e.g. port in use). If you want extra sanity you can put a `console.log` inside your server function - that way your terminal can confirm it's heard the request! – Gershom Maes Mar 28 '19 at 18:34
  • What command are you using to load the server? Just double check you're using 'node myFileName.js' - other than that the only issue I could possibly see is that you're already using the port 8080 with another program – teamyates Mar 28 '19 at 18:38
  • replace port 8080 with 8081 and open `http://localhost:8081` in your browser – Vikash_Singh Mar 28 '19 at 19:32

2 Answers2

1

It would be a good approach to get the PORT environment variable and to have the server listen on that port, instead of one that is hard-coded.

In node you can get this with: var port = process.env.PORT || 8080

This is saying that if the PORT environment variable is set use that OR use 8080 if it is not set.

Your new code would be:

var http = require('http');
var port = process.env.PORT || 8080;

http.createServer(function (req, res) { 
   res.writeHead(200, {'Content-Type': 'text/html'});
   res.end('Hello World! i did it');
}).listen(port);
Jared Forth
  • 1,577
  • 6
  • 17
  • 32
0

If you are using Windows CMD, first type 'node'. Now you will be coding directly in node.js. Now, copy and paste your code, and hit enter. Now go, and try the localhost:8080 on your browser.

If you still have the issue, try the same with a different port. I tested your code on my machine and works perfectly fine.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Raj006
  • 562
  • 4
  • 18