Muhammad Imran Ansari
How can you create Http Server in Nodejs?

How can you create Http Server in Nodejs? Why you need it?

By Muhammad Imran Ansari in .NET on Jan 30 2023
  • Tuhin Paul
    Feb, 2023 22

    In Node.js, you can create an HTTP server using the built-in http module. Here’s an example code to create a basic HTTP server:

    1. const http = require('http');
    2. const server = http.createServer((req, res) => {
    3. // set response header
    4. res.writeHead(200, { 'Content-Type': 'text/plain' });
    5. // write response message
    6. res.write('Hello World!');
    7. // end the response
    8. res.end();
    9. });
    10. // listen on port 3000
    11. server.listen(3000, () => {
    12. console.log('Server started on port 3000');
    13. });

    In the above code, http.createServer() method creates a new instance of http.Server. It takes a callback function with two arguments - req and res. The req object represents the client request and the res object represents the server response.

    Inside the callback function, we set the response header using res.writeHead() method and write the response message using res.write() method. Finally, we end the response using res.end() method.

    To start the server, we use the listen() method of the http.Server object. It takes two arguments - the port number to listen on and a callback function that is executed when the server is ready to accept requests.

    • 1
  • Jin Necesario
    Feb, 2023 4

    You can use the HTTP module.

    Using this module there’s a createServer function that turns your localmachine into a HTTP server.

    See the sample code below.

    1. /**
    2. * Node.js has a builtin HTTP module which gives us
    3. * the ability to transfer over HTTP.
    4. */
    5. const http = require("http");
    6. /*Let's create a simple web server*/
    7. http.createServer((request, response) => {
    8. response.write("Hello Web Sever");
    9. response.end();
    10. }).listen(9090);

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS