DEV Community

miku86
miku86

Posted on • Updated on

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
Enter fullscreen mode Exit fullscreen mode
  • 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}/`);
});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • Result:
Server running at: http://localhost: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 express or some libraries like koa or sails? Why do you use it?

Top comments (1)

Collapse
 
waqar903 profile image
waqar903

Nice works..!
Can you please tel how can i upload Expressjs and MongoDB api on live server? with my domain hosting?
for now its
Server running at: localhost:8080/
i want
Server running at: example.com/api