have you been working on backend technology and thinking to create development server. so you are on right place here you learn about Html CSS JavaScript to create simple web app with short and easy tutorial with explanation.
Hello guys starting to create REST API [Representable State, Application Programing Interface] with NODE.js & EXPRESS.js creating live server.
Step 1: initialize node.js in your computer
node.js very popular Java Script framework on backend to create server and reliable for creating java script run time environment everywhere.
if you have not installed yet then install from nodejs.org and setup path for node.js then open your terminal in computer and run following for checking node.js successfully setup.
node –v
npm -v
if you showing version then node is exist. now initialize project run following code:
mkdir my-rest-api
cd my-rest-api
npm init -y
Step 2: Install Express.js:
for handling HTTP Request we can install express. Express is a popular and really cool Node.js framework that is designed to help create server really Quickly
Run npm install express command in your power shell or terminal to install the Express.js framework.
npm install express
Step 3: Create an Entry File: A basic node file contain a package. json. open file manager and Create an index.js file into project directory. open this in vs code This will be your entry point.
const express = require(‘express’);
const app = express();app.listen(3000, () => {
console.log(“Server running on port 3000”);
});
This code create Express server that listens on port 3000.
Step 4: Set Up Express.js: Import Express in index.js and set up a basic server Environment.
Step 5: Define Routes for handling HTTP method: Create routes for your API to handle GET, POST, PUT, and DELETE requests.
Get Request: for get request paste this code in your project app.get file. For return a simple message.
app.get(“/msg”, (req, res, next) => {
res.json({“message”: “Hello, World!”});
});
Post Request:
app.use(express.json()); // for parsing application/json
app.post(“/msg”, (req, res, next) => {
const message = req.body.message;
res.json({“receivedMessage”: message});
});
PUT Request:
DELETE Request:
Step 6: Start the Server: Have your server listen on a port to start accepting requests.
following code snippet:
|
Step 7: Testing Your Rest API
for get Request you can simply visit http://localhost:3000/msg in your browser.