Dino Geek, try to help you

How to use HTTP module in Node.js?


Here is a simple example of how to use the HTTP module in Node.js:

1. In order to use the HTTP module, you need to require it. This is done by using `require(‘http’)`.

```
const http = require(‘http’);
```

1. Next, you’re going to create the server using the createServer method.

```
const server = http.createServer((req, res) => { res.writeHead(200, {‘Content-Type’: ‘text/html’}); res.end(‘Hello World!’);
});
```

In this example, we create a function that has two parameters (‘req’ and ‘res’) representing the request and the response objects of the server. The `writeHead` method sends a response header to the request. The first parameter is the status code, 200 means that all is OK, the second parameter is an object containing the response headers. The `end` method is used to end the response process, if no argument, a blank message is displayed.

1. Finally, you tell your server to listen for requests on a specific port:

```
server.listen(3000, ‘localhost’, () => { console.log(‘Server listening on port 3000’);
});
```

This method causes server to listen to specified port (3000 in this case). Once the server starts listening, the callback function is executed.

Let’s put them together:

```
const http = require(‘http’);

const server = http.createServer((req, res) => { res.writeHead(200, {‘Content-Type’: ‘text/html’}); res.end(‘Hello World!’);
});

server.listen(3000, ‘localhost’, () => { console.log(‘Server is listening on port 3000’);
});
```

With the above code, you have created a simple web server in Node.js using the HTTP module and when you navigate to ‘http://localhost:3000’ in your browser, you should see “Hello World!”.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use