Hey Guys!
Want to know how to create your own Server with Express?
Well, Let's get started!
First, fire up a terminal and create a directory. If you don't know how to access the terminal, check out my other blog:
Next, go to the NPM Website and open this package called Express. Here is the link:
Next, fire up your terminal and type
npm install express
to install the package. It will go through a quick process and it will install:
Now, create a constant called express require it:
//jshint esversion:6
const express = require("express");
const app = express();
Now, use the app.get method:
app.get("/", function (request, response) {
response.send();
});
The app. get() method specifies a callback function that will be invoked whenever there is an HTTP GET request with a path ( '/' ) relative to the site root:
Then, use the app.listen method:
app.listen(3000, function (){
console.log("Server started on Port 3000");
});
The app. listen() function is used to bind and listen the connections on the specified host and port.
Now In the app.get method, in respond.send, you can add strings, HTML code and many more.
For this tutorial I will be adding HTML Code. So you can write something like this:
response.send("<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>
<h4>This is a heading</h4>
<h5>This is a heading</h5>
<h6>This is a heading</h6>");
Now, you can open up your terminal again, make sure you are in the express server directory and type node server.js
(Installing Node is required):
Finally, go to your browser and type localhost:3000
and VOILA you can see the content. This means you have successfully created an express server:
If you like this blog then do like it and comment down below.
If you have any questions, do reach out to me in the comments.
Thank You and stay tuned for blogs about our Best Friend Coding!
Remember...
Top comments (0)