DEV Community

miku86
miku86

Posted on • Edited on

12 5

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?

Top comments (4)

Collapse
 
terenson profile image
terenson

Is it possible to start something similar via https ?

Collapse
 
miku86 profile image
miku86 • Edited

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

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay