How to Setup a Server Using Express?

How to Setup a Server Using Express?

Step 1:

For making the simple server in express you have to first install the node js in your machine. By clicking the link you can download it.

official website of Nodejs

Step 2:

After installing the node js check whether it is downloaded or not

for this, you can use the command in your terminal.

node -v

Step 3:

Open any IDE (recommended VS code) create any folder and then create a file inside it (like -server.js) and then open Tenimal (ctrl +j) and then run the command.

npm install express

This will install Express into your folder.

Step 4:

I am taking the server.js file for code.

we need to require (express ) it to be able to use it. At the top of the page, we are going to write these two lines of code. It should be at the top of the page(recommended).

const express = require("express");
const app = express();

Now Creating the Server

const port = 3000;
app.get('',(req,resp)=>{
resp.send(__dirname + "/index.html");
});

app.listen(port,()=>{
  console.log(`Server running on port ${port}.`);
});

That's it we are all done! We created a server using Express and used it to display our index.html file on our home page.

Step 5:

Running the server.

In the root directory of your project, open the terminal and use this command.

node server.js

Now go to your browser and type in:

localhost:3000

If you see a blank page that is because you need to add content to your index.html file. otherwise, you can also do this

resp.send("Hello express");

Thank you for reading my content. Be sure to follow and comment on what you want me to write about next.

Did you find this article valuable?

Support Saurabh verma by becoming a sponsor. Any amount is appreciated!