NodeJS: How To Create A Simple Server Using Express

Intro

So we installed NodeJS on our machine.

We also learned how to create a simple server using Node's HTTP module.

We also know How to Get External Packages.

Now we want to learn how to create a simple server using express.

Write a simple script

  • Open your terminal
  • Create a file named index.js:
touch index.js
  • Add this JavaScript code into it:
// import express (after npm install express)
const express = require("express");

// create new express app and save it as "app"
const app = express();

// server configuration
const PORT = 8080;

// create a route for the app
app.get("/", (req, res) => {
  res.send("Hello World");
});

// make the server listen to requests
app.listen(PORT, () => {
  console.log(`Server running at: http://localhost:${PORT}/`);
});

Note: This simple server has only one working route (/). If you want to learn more about Routing, read the docs for Routing.


Run it from the terminal

  • Run it:
node index.js
  • Result:
Server running at: http://localhost:8080/

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


Further Reading


Questions

  • Do you use express or some libraries like koa or sails? Why do you use it?