DEV Community

sonicx180
sonicx180

Posted on

Create an Express Server

How to Create an Express Server.

I recommend this only for beginners since it's so basic.

Step 1:
Create a folder and name it whatever you like.
Go to your terminal and run (cd folder name likecd myapp )and run npm init -y

Go to a text editor (like VSC or Caret or Sublime Editor) and open the index.js file

Then write this in your file:

const express = require("express");
const app = express();
Enter fullscreen mode Exit fullscreen mode

The first line of code imports the express module.
The second line of code initializes an express app.

But the app isn't really running yet.

Write these lines of code after the code above.

app.get('/', (req,res) => {
 res.send("Hello World!")
}
app.listen(3000, (err) => {
if (err) console.log(err)
else console.log("Server Running on port 3000")
}
Enter fullscreen mode Exit fullscreen mode

Now, to break this down.

For the first three lines of code, on the homepage (like https://dev.to) it will show Hello World!. By the way, read about arrow functions here https://www.w3schools.com/js/js_es6.asp. req stands for request and res stands for response.
As for the rest of the code, the app.listen function makes the app listen on port 3000 and there is an error logger too.

Now go to your terminal and run cd (your folder name) like cd myapp. After that run npm i express. Then run node index.js. Your app should be up and running !

If this doesn't express much, go to Free Code Camp back end development or go to Express Js.

Well, that's about it. Comment if you have any suggestions. Thanks for reading!

Top comments (0)