0

I am new at Node Js, sorry if the question is irrelevant but just wanted know that, what is the proper way of sending an HTML response to the browser. In the simple example code below I've put the server inside the readFile method is that okay, I will probably need to create a server for each file that way. It's definetly not the right way of doing it. What is the proper way of handling requests and responds in Node Js.

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

if (fs.existsSync('../Html')) {
  fs.readFile('../Html/index.html', (err, data) => {
    if (err) throw err;

    const server = http.createServer((req, res) => {
      console.log('The request is made');
      res.setHeader('Content-Type', 'text/html');
      res.write(data.toString());
      res.end();
      console.log(req.url, req.method);
    });
    server.listen(3000, 'localhost', () => {
      console.log('Listening for the localhost:3000');
    })
  });
}

1 Answer 1

1

The slightly more proper way is to analyze your request:

const server = http.createServer((req, res) => {
   switch (req.path) {
   case '/': // process index
   case '/about': // process other routes and so on
   // ...
   }
})

However, this is not how real applications are built. Almost anyone would use an application framework to facilitate complex routing.

You may want to look, e.g. into express.js.

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

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.