DEV Community

miku86
miku86

Posted on • Edited on

18 9

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

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay