1

I m using following code for creating server with node js but whenever i run local host on this port in browser it always show index.html file. What is wrong i do ..

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'html'});
    res.end(index);
}).listen(9615);
2
  • 1
    It appears to be doing exactly what you told it to. What were you expecting to happen? Commented Aug 30, 2014 at 6:43
  • I am expecting to access my another pages like views/about.html and views/main.html but whenever i try to access these pages it always open index.html? Commented Aug 30, 2014 at 6:47

2 Answers 2

2

What you want is to create a router.

Check this: http://www.nodebeginner.org/

Sign up to request clarification or add additional context in comments.

1 Comment

g.mail cyber police: can you provide me generic function for routing in nodejs..i didnt understand from the begginerwebiste.
0

If you come from a php background, you may expect that creating a file on the server makes it accessible throught an url containing its file name.

In node.js, things work differently. You must use a routing system. Basically, you are going to tell that the "route" (url) views/about is the file about.html.

I think that the best option for you is to install Express framework : it will create basic routes for you, then you'll just have to copy and change some lines to set up new ones.

Express is also going to make a lot of other stuff easier and faster to develop

Have a look at this 5 min Express tutorial

3 Comments

van you provide me code for generic routing in nodejs
Express is a generic routing system.
simply install express with npm and follow any tutorial on the internet. it will be pretty straightforward

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.