0

I have a small script that runs a server for static index.html file:

var http = require('http');
var fs =require('fs');


var server = http.createServer(function(req,res){
    console.log('request was made : '+req.url);
    res.writeHead(200,{'Content-Type':'text/html'});
    var myReadStream  = fs.createReadStream(__dirname +'/index.html','utf8');
    myReadStream.pipe(res);
});

server.listen(3000,'127.0.0.1');

console.log('listening to 3000');

Is the a possibility to use a string instead of 'localhost:3000' say for example 'MyPAGE' to call the html file?

3
  • Do you mean http://localhost:3000/MyPAGE? Or do you want to type MyPAGE in browser address bar? Commented Jul 5, 2019 at 9:35
  • thanks for replying I mean 'MyPage' without anything else ! Commented Jul 5, 2019 at 9:36
  • It's better to use a web server for that, like nginx or apache. Commented Jul 5, 2019 at 9:37

2 Answers 2

7

A URL consists of several parts:

     foo://example.com:8042/over/there?name=ferret#nose
     \_/   \______________/\_________/ \_________/ \__/
      |           |            |            |        |
   scheme     authority       path        query   fragment
      |   _____________________|__
     / \ /                        \
     urn:example:animal:ferret:nose

In your example:

  • The scheme is omitted, but the browser is implicitly adding http:// because you are typing it into the address bar.
  • The authority is made up of a hostname and a port
    • The hostname is localhost
    • The port is 3000
  • The path is omitted and defaults to /
  • Everything else is omitted and has no content

In order for you to use MyPage you need:

  • The port to be 80 (which is the default for HTTP, so you can only omit it if you use the default port)
  • Your browser to resolve the hostname MyPage to the same IP address as localhost (127.0.0.1 in this case)

So you need to:

  1. Change server.listen(3000,'127.0.0.1'); to server.listen(80, '127.0.0.1');. Keep in mind that port 80 is a priviliged port so you will need to be a root/Administrator account to run a service there.
  2. Configure your DNS or /etc/hosts so that MyPage resolves to the right IP address.
Sign up to request clarification or add additional context in comments.

Comments

2

localhost is nothing but the local server IP i.e. 127.0.0.1 to change string localhost with MyPAGE you need to register hostname against local server IP

For windows edit c:\Windows\System32\Drivers\etc\hosts and add 127.0.0.1 MyPAGE NOTE: you need to open this file as admin.

For linux edit - /etc/host file and add 127.0.0.1 MyPAGE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.