API | Create a Fully Working API with Node.js and Express - EHB
In this post I am going to show you how you can create an API to get some data with the help of Node.js and Express. Here we are going to create a simple API that sends the word "Hello". Let's get started now that you know what we are going to do.
Make sure you have installed and setup Node.js on your computer. If you haven't installed it yet, then you can download it here. We will be using Hyper Terminal in this post. You can use any terminal you are familiar with.
Step 1: Create a folder called "backend"
In the first step, we are simply going to create a folder named "backend". You can name it whatever you want. You can create a folder in two ways:
- Making Use of the Mouse
Use a mouse or trackpad and "Right-Click > New > Folder". - Making Use of Terminal
Open the Terminal and use the cd command to go to the location where you want to create the folder. For simplicity's sake, I am going to create the folder on my desktop. So I will use the following command.cd Desktop/ mkdir backend
Step 2: Create a file "app.js" in the "backend" folder.
In this step, we are going to create a file "app.js" inside the periviously created folder "backend". You can name it whatever you want, but make sure that your file is saved with a ".js" extension. You can do this in two ways:
- Making Use of the Mouse
Use a mouse or trackpad and do a double click on the folder. After it opens, do "Right-Click > New > Text Document" and rename the file. - Making Use of Terminal
Open the Terminal and use the cd command to go to the location of the folder. Now use "touch" command to create a file.cd backend/ touch app.js
Step 3: Initialize npm using the "npm init" command.
After creating the "app.js" file, write "npm init" in the terminal. It will initialise the "npm" and walk you through a utility to create a "package.json" file. You just have to press enter until you see "Is this OK? (yes)" in the terminal and press enter one last time. If you don't want to press enter so many times, then you can use the "npm init -y" command. This command will automatically create a "package.json" file with default values.
Step 4: Install the "express" package using npm.
After step 3, write "npm i express" to install the express package to the "package.json" file as a dependency.
Now open "app.js" and write the code below in it:
const express = require("express"); const app = express(); app.get("/", function(req,res){ res.send("Hello"); }); app.listen(3000, function(){ console.log("Server is running on port 3000");});
Comments
Post a Comment