DEV Community

miku86
miku86

Posted on • Updated on

NodeJS: How To Create A Simple Server Using The HTTP Module

Intro

So we installed NodeJS on our machine.

Now we want to learn how to create a simple server using the HTTP module.

Write a simple script

  • Open your terminal
  • Create a file named index.js:
touch index.js
Enter fullscreen mode Exit fullscreen mode
  • Add this JavaScript code into it:
// import http module
const http = require('http');

// server configuration
const HOST = '127.0.0.1';
const PORT = 8080;

// create the server
const server = http.createServer((req, res) => {
  res.end('Hello!');
});

// make the server listen to requests
server.listen(PORT, HOST, () => {
  console.log(`Server running at: http://${HOST}:${PORT}/`);
});
Enter fullscreen mode Exit fullscreen mode

Note: This is an extremely simple server. I would recommend you to read the docs of the HTTP module, especially how headers work and how to send them.


Run it from the terminal

  • Run it:
node index.js
Enter fullscreen mode Exit fullscreen mode
  • Result:
Server running at: http://127.0.0.1:8080/
Enter fullscreen mode Exit fullscreen mode

Now you can click on the link and reach your created server.


Further Reading


Questions

  • Do you use the native HTTP/HTTPS module or some libraries like express? Why do you use it?

Discussion (4)

Collapse
terenson profile image
terenson

Is it possible to start something similar via https ?

Collapse
miku86 profile image
miku86 Author • Edited on

Hey @terenson ,

great question.

Like @arswaw said,
you need a certificate.

How to create an https server?
Node HTTPS Module

Collapse
arswaw profile image
Arswaw

Yes but you have to have a certificate.

Collapse
pandax54 profile image
pandax54

Thank you so much for sharing this! =) Dankeschon