Setup a Node.JS application:
Step 1:
Make sure you have Node.Js and npm downloaded
Step 2:
Create a new folder, and open a terminal on the folder
Step 3:
In the terminal, run `npm init -y`
Now you should see a file named package.json in your folder
Step 4:
Add a index.js file in the root of your project
Creating your first Node.JS application with Express.Js
Go to index.js file:
Step 1:
Add the following code in the file:
// Import the express library
const expressApp = require("express")
// define the port
const PORT = 9000
// create the app (server) by calling the expressApp function
const app = expressApp()
// call the "listen" method on the app instance,
// provide it with a port on which it should be open for connections
app.listen(PORT, () => console.log(`The server is running on port: ${PORT}`))
Creating your first Node.JS application with Express.Js
Go to index.js file:
Step 2:
Add your first API
// Import the express library
const expressApp = require("express")
// define the port
const PORT = 9000
// create the app (server) by calling the expressApp function
const app = expressApp()
// add the HTTP Method (get) on your app,
// define the path: "/users",
// add the logic
app.get("/user", (req, res, next) => {
const { query, params, body } = req
console.log({query, params, body})
res.status(201).send("Users are there")
})
// call the "listen" method on the app instance,
// provide it with a port on which it should be open for connections
app.listen(port,
() => `The server is running on port: ${PORT}`)
Creating your first Node.JS application with Express.Js
Go to index.js file:
Step 3:
Test your app:
Run `npm start`
Check the package.json -> scripts -> start
{
"name": "my-node-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js"
}
}
npm start
After you have done 'npm init -y', you get a package.json file in your folder.
This file has several data in an object:
name:
the name of your NodeJS app
main: entrypoint of your NodeJs app, the code execution starts from this very file.
{
"name": "my-node-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js"
}
}
npm start
version
: it indicates the version of your NodeJs application. It's important when you're deploying your code.
This version is of 3 numbers (1.0.0):
- Major update (1)
- Minor update (0)
- Patch update (0)
This is called semantic versioning.
{
"name": "my-node-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js"
}
}
scripts:
this contains scripts or commands that you can run from terminal directly using package manager (npm).
You can run in terminal npm run <scripts-key>
Eg:
npm run start
npm run hello
{
"name": "my-node-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js",
"hello": "echo \"hello world\""
}
}
dependencies:
Dependencies are the libraries that we need to run our NodeJs application.
devDependencies:
Now the devDependencies are the libraries that are required for development, but are not required to run our application, they can be put in devDependencies.
This keeps our production build lightweight.
{
"name": "tapish-test",
"version": "2.7.7",
"main": "src/server.js",
"scripts": {
"test": "echo \"nhi krna hai koii test\"",
"dev": "nodemon src/server.js",
"prod": "node src/server.js"
},
"dependencies": {
"body-parser": "^1.20.2",
"express": "^4.19.1",
"pg": "^8.12.0"
},
"devDependencies": {
"nodemon": "^3.1.3"
}
}
npm i express
npm i express@4.19.2
npm i nodemon --save-dev
npm i nodemon@3.1.3 --save-dev
const bodyParser = require("body-parser");
const expressApp = require("express");
const server = expressApp();
const PORT = 2334;
const userMap = {
user1: {
id: "Yash",
password: "Asdasd",
}
};
// parse application/json
server.use(bodyParser.json());
server.post("/user-post", (req, res, next) => {
const { query, body, params } = req;
console.log({ body, query, params });
Object.assign(userMap, body);
res.status(201).json(userMap);
});
server.get("/user-get", (req, res, next) => {
console.log("user posted");
res.status(203).json(userMap);
});
server.get("/login", (req, res, next) => {
const { userid, password } = req.body;
const user = Object.keys(userMap).find((user) => {
return userMap[user].id === userid && userMap[user].password === password;
});
if (user) {
res.status(203).json(user);
} else {
res.status(401).json("User not found");
}
});
server.listen(PORT, () => console.log(`Server is listening on PORT: ${PORT}`));
Creating POST APIs,
Create GET APIs
Sending Response as JSON
Passing data through API in queryParams
Passing data through API in body
Using bodyParser for accessing API body data,
Sending different HTTP status codes in response
const bodyParser = require("body-parser");
const expressApp = require("express");
const server = expressApp();
const PORT = 2334;
const userMap = {
user1: {
id: "Yash",
password: "Asdasd",
}
};
// parse application/json
server.use(bodyParser.json());
server.post("/user-post", (req, res, next) => {
const { query, body, params } = req;
console.log({ body, query, params });
Object.assign(userMap, body);
res.status(201).json(userMap);
});
server.get("/user-get", (req, res, next) => {
console.log("user posted");
res.status(203).json(userMap);
});
server.get("/login", (req, res, next) => {
const { userid, password } = req.body;
const user = Object.keys(userMap).find((user) => {
return userMap[user].id === userid && userMap[user].password === password;
});
if (user) {
res.status(203).json(user);
} else {
res.status(401).json("User not found");
}
});
server.listen(PORT, () => console.log(`Server is listening on PORT: ${PORT}`));
Request: When API call is made from the client (React) to the server (NodeJs)
Response: The server (Nodejs, receives the request, and it replies/sends a response back.
Request and Response have some important parts:
Authorization
Basic <base64-encoded-credentials>
Bearer <token>
Digest <parameters>
Usage Example:
// Basic Authentication:
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
// This encodes the username and password in base64
// and sends it to the server for basic authentication.
// Bearer Token (JWT):
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
// This sends a JWT token to authenticate API requests.
Content-Type
text/html
application/json
multipart/form-data
Usage Example:
// Sending JSON Data:
Content-Type: application/json
// This header is used when sending
// JSON data to the server.
// Uploading a File:
Content-Type: multipart/form-data
// This is used for file uploads in forms.
Accept
text/html
application/json
image/png
Usage Example:
// Accepting JSON Responses:
Accept: application/json
// This informs the server that the client expects a JSON response.
User-Agent
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
Usage Example:
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
// This header identifies the client's browser and operating system.
Cache-Control
no-cache
no-store
max-age=<seconds>
Usage Example:
// Fetching Fresh Data:
Cache-Control: no-cache
// This ensures that the request fetches
// fresh data rather than using a cached response.
// Caching for an Hour:
Cache-Control: max-age=3600
// This tells the cache to store the
// response for one hour.
Referer
Referer: https://example.com/previous-page
Usage Example:
Referer: "https://example.com/home"
// This informs the server about the origin
// of the request for tracking purposes.
Content-Type
text/html
application/json
image/jpeg
Usage Example:
// Returning JSON Data:
Content-Type: application/json
// This indicates that the
// response body contains JSON data.
Content-Length
Content-Length: 348
Usage Example:
Content-Length: 1024
// This informs the client about
// the size of the data being transferred.
Cache-Control
no-cache
no-store
max-age=<seconds>
Usage Example:
// Caching Static Assets:
Cache-Control: public, max-age=86400
// This tells the cache to store the response for a day,
// which is useful for static assets like images.
Set-Cookie
Set-Cookie: <name>=<value>; Expires=<date>; Path=<path>; Domain=<domain>; Secure; HttpOnly
Usage Example:
Set-Cookie: sessionId=abc123; Path=/; HttpOnly
// This sets a session cookie to maintain
// user sessions across multiple requests.
Location
Location: https://example.com/new-page
Usage Example:
Location: "https://example.com/login"
// This redirects the client to the login
// page after successful registration.
Access-Control-Allow-Origin
*
(any origin)Access-Control-Allow-Origin: https://example.com
Usage Example:
// Allowing Any Origin:
Access-Control-Allow-Origin: *
// This allows any origin to access the resource.
// Specific Origin:
Access-Control-Allow-Origin: https://example.com
// This allows only example.com to access the resource.
// server.js
const express = require('express');
const app = express();
const port = 3000;
// Import users routes
const usersRouter = require('./routes/users');
// Use users routes
app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on
http://localhost:${port}`);
});
// routes/userRoutes.js
const express = require('express');
const router = express.Router();
// Define routes for users
router.get('/', (req, res) => {
res.send('Hello, World!');
});
router.get('/:id', (req, res) => {
res.send('About Page');
});
router.post('/submit', (req, res) => {
res.send('Form submitted');
});
module.exports = router;
// server.js
const express = require('express');
const app = express();
const port = 3000;
// Home route
app.get('/users/', (req, res) => {
res.send('Hello, World!');
});
// About route
app.get('/users/:id', (req, res) => {
res.send('About Page');
});
// Example of a POST route
app.post('/users/submit', (req, res) => {
res.send('Form submitted');
});
app.listen(port, () => {
console.log(`Server is running
on http://localhost:${port}`);
});
// server.js
const express = require('express');
const app = express();
const port = 3000;
// Import users routes
const usersRouter = require('./routes/users');
// Use users routes
app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on
http://localhost:${port}`);
});
// routes/userRoutes.js
const express = require('express');
const router = express.Router();
const getUserById = require('/controllers/getUserById')
// Define routes for users
router.get('/', getUserById);
router.get('/:id', (req, res) => {
res.send('About Page');
});
router.post('/submit', (req, res) => {
res.send('Form submitted');
});
module.exports = router;
// controllers/getUserById.js
const express = require('express');
const router = express.Router();
// Define routes for users
const getUserById = async (req, res, next) => {
res.status(200).json('Hello, World!');
});
module.exports = {
getUserById
};
const express = require('express');
const app = express();
// Middleware function
const loggerMiddleware = (req, res, next) => {
console.log(`${req.method} ${req.url}`);
// Pass control to the next middleware or route handler
next();
};
// Apply middleware to all routes
app.use(loggerMiddleware);
// Route handlers
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.post('/submit', (req, res) => {
res.send('Form submitted successfully!');
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Middlewares In Express:
(req),
response object (res)
, and the next
function in the application's request-response cycle.bodyParser.json(),
cors()
const express = require('express');
const app = express();
const router = express.Router();
// Middleware function
const authMiddleware = (req, res, next) => {
if (req.query.token === 'secret_token') {
next(); // Proceed to the next middleware or route handler
} else {
res.status(401).send('Unauthorized');
}
};
// Apply middleware to the router
router.use(authMiddleware);
// Route handlers
router.get('/', (req, res) => {
res.send('Welcome to the protected area!');
});
router.post('/create', (req, res) => {
res.send('Resource created successfully!');
});
// Mount the router on a path
app.use('/api', router);
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Middlewares In Express:
authMiddleware
function checks if a query parameter token
with a value of 'secret_token'
is present in the request.router.use(authMiddleware)
./api
path usingapp.use('/api', router)
.