Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Node

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 54

Backend - Development

Backend - Development

Backend Development also commonly known as server - side development. It consists of three
parts

• Server : Whenever the front-end application is making an request to get data from the database
it will first of all come to the server. It connects your backend application with the frontend
application.

• Backend application : This is the application that backend developer develops which accepts
requests from the server and whatever is requested, this app will query the database and will
provide the desired output.

• Database : Whatever data you see on any website, all the data other than static headings or
information comes from the database.
Server & Backend Database
Frontend
Node.JS
• Any javascript application can be run only on browser, because to execute JS code
we need JS engine that is present only in browsers like Chrome has V8, Explorer
has Chakra.
• But Ryan Dahl, wrote some code using C, C++, Javascript and executed it using V8
engine, this code is now commonly known as Node.JS, this allows us to execute the
JS code outside the browser.
• Node.js is an open-source, cross-platform, JavaScript runtime environment built on
Chrome's V8 JavaScript engine that executes JavaScript code outside a web browser
Create a simple server
• Now, we will first understand that how we can create a server.
• By using “http” module given by JS, we can create the server.
• We can send plain text, HTML, JSON responses from this module.

const http = require("http");

http.createServer(function(request, response){
response.write(“Hello World”);
response.end();
}).listen(3000)
Create a simple server
• Few key points to remember when you are creating any server :
• We will be using createServer function from http module. This function takes
in two parameter request and response.
• If you want to show some response on the screen or give some response on
the url then use response
• If you want to see that what url is providing then check the request parameter.
• Make sure that you end the response else you will not be able to see the
response.
• Whenever you make any changes in server side application, make sure you
cave the changes and restart the server to see the new changes.
• Make sure you add some port number where you want to run you application.
Send HTML Response
const http = require("http");

http.createServer(function(request, response){
response.write(“<h1>Hello</h1>”);
response.end();
}).listen(3000)
Send JSON Response
const http = require("http");

http.createServer(function(request, response){
const user = {name: “John”, age:23}
response.write(“<h1>Hello</h1>”);
response.end(JSON.stringify(user));
}).listen(3000)
Exercise : 1

Create a server using HTTP module,


1.Send response using plain text , response on screen should be Hello world
2.Send response using HTML, response on screen should be the explanation
of Node.JS
3.Send JSON response, a student details like name, age, email, contact,
course, date of joining.
Express
Express
• Creating APIs by just using pure Node.JS will become difficult if your application will
grow which will happen eventually, this is the reason why we use this framework

• With a myriad of HTTP utility methods and middleware at your disposal, creating a
robust API is quick and easy.

• Express provides a thin layer of fundamental web application features, without


obscuring Node.js features that you know and love.

• Many popular companies are using Express in their application.


teps to start with express

• Create a folder and start with command “npm init” : This command will create a
package.json file in your folder. It is required because we will installing express
framework to build the application.

• Next we need to install the express, so use this command “npm install express” : This
command will install the express in your folder, you can verify by checking express
keyword in dependencies object in package.json file.
reate server using express
const express = require("express");
const app = express();

app.get('/', function(req, res){


res.send("Hello world");
})

app.listen(3001)
Exercise : 2

Create a server using express,

1.Send JSON response, a student details like name, age, email, contact,
course, date of joining.
Exporting Modules
When you are creating backend application we will not be having complete data in the
same file where we have created our server. So we storing or manipulating the data in
separate files and will import those files in main file and send in the api response

const express = require("express");


const data = require('./data')
const app = express();

app.get('/', function(req, res){ exports.technology = ["React", "Node", "JS"]


console.log(data.technology);
res.send("Hello world");
})

server.js
app.listen(3001) data.js
Express Routing
Express Routing
Routing is nothing but different urls which will be providing different data. For ex: when
you are trying https://localhost:3001/ you are actually pointing at “/“ route. But when
developing a big application you will need to build a lot of routes, that is knows as
Express Routing.
const express = require("express");
const data = require('./data')
const app = express();

app.get('/', function(req, res){


res.send(“Main route");
})
app.get('/user', function(req, res){
res.send(“User route");
})
Exercise : 3

Create a separate file which is containing a student’s data and a function. Task is to
import this file in the main server.js file where you have created your server using
express. Now from this file you have to send this data in response from the route
like /student.
Middleware
Middleware
• Middleware are like any general functions which takes in three parameters as request,
response and next function.
• These middleware are used to execute some function before the response is send back
to the client.
• It mostly gets used for the authentication, that before we send the response, we can
authenticate if the API request is called from the client with proper user credentials or
not.
• These middleware can be applied on the whole application level as well as on one
particular API route.
• next() function is very important, after the end of each middleware we should execute
next function so that the program execution can move either to next middleware or to
main route, if this function is not added then execution will not move forward.
iddleware - On whole application
const express = require("express");
const app = express();

• In this we have written a function


const middleware1 = (req, res, next)=>{
named middleware1, this is working console.log("middleware1");
as middleware, it takes in 3 next()
}
arguments req, res, next.
app.use(middleware1);
• app.use(middleware1), this will apply
the middleware on the whole app.get('/', function(req, res){
res.send("Main route");
application.
})

app.listen(3001)
Middleware - On specific route
const express = require("express");
const app = express();

• When you want to run the middleware const middleware1 = (req, res, next)=>{
console.log("middleware1");
on a specific route then pass the next()
middleware function in the route }

function itself.
app.get('/', middleware1, function(req, res){
res.send("Main route");
})

app.listen(3001)
Exercise : 4

Create two middlewares and 4 routes, one middleware should be applied on all the
routes and second middleware should be applied on only two routes. Routes can be
/about /home /contact /courses. Second middleware should be applied on /home
and /courses.
Express Params

• There are two types of parameter : URL parameter, Query parameters

• URL parameters : It is an individual value, means single value will be coming in


the url like sending productID. Ex : https://localhost:3001/1234

• Query parameters : In this case values comes in key value pair. It comes with
syntax like “ ? Key = value “. It can be passed in cases like sending student
name. Ex : https://localhost:3001/p?tagid=1234
Express Params

• There are two types of parameter : URL parameter, Query parameters

• URL parameters : It is an individual value, means single value will be coming in


the url like sending productID. Ex : https://localhost:3001/1234

• Query parameters : In this case values comes in key value pair. It comes with
syntax like “ ? Key = value “. It can be passed in cases like sending student
name. Ex : https://localhost:3001/p?tagid=1234
Express : URL Params
const express = require("express");
const app = express();

• When url is http://localhost:3001/12


app.get('/:id', function(req, res){
console.log(req.params.id);
res.send("Helo")
})

app.listen(3001)
Express : Query Params
const express = require("express");
const app = express();

• When url is http://localhost:3001/?name=John app.get('/', function(req, res){


console.log(req.query.name;
res.send("Helo")
})

app.listen(3001)
Exercise : 5

Create two routes :


1. One route should be able to retrieve the productId from the url ex:
https://localhost:3000/product/32
2. Another route should be able to extract user information from the url ex:
https://localhost:3000/?firstName=John?lastName=Doe?department=HR
Postman
• It is a tool which lets you check the APIs and their response.
• You can also set information like authorisation token or any other parameters
required to execute the API.
• You can download postman from here https://www.postman.com/downloads/
HTTP methods
• GET : GET is used to request data database or any other resource.

• POST : POST is used to send data to a server, this data will be considered as new
entry in the database.

• PUT : PUT is used to send data to a server, this data will be used to update some
value in database.

• DELETE : DELETE is used to send data to a server, this data will be used to delete
some value in database.
HTTP status codes
There are a lot of status codes. But few status codes are extremely important :
• 200 : This is the standard “OK” status code for a successful HTTP request.
• 401 : This status code request occurs when authentication is required but has
failed or not been provided.
• 404 : A status code 404 occurs when the request is valid, but the resource
cannot be found on the server.
• 500 : The status code 500 happens when the server cannot fulfill a request due
to an unexpected issue

Refer this site to see other status codes


https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
React and Node
Now comes is that how will you integrate the front-end application which is written in
React and backend application which is written in Express. Follow the below mentioned
steps :
• Once your server development is completed then set some port number other than
3000 like 3001, 8080, 5000 etc. because react application must be running on
3000 port. Both the application should be running on different ports. You have to
keep the backend application up and running.
• Now your apis calls you are writing in either componentDidMount or useEffect or
any other place, at every place you will have to change the url as
https://localhost:8080, assuming your backend application is running on 8080
port.
• Now your server is running on 8080 port and front-end is running on 3000 port and
body-parser

• body-parser extracts the entire


body portion of an incoming const express = require("express");
const app = express();
request stream and exposes it
Const bodyParser = require(“body-parser”);
on req.body
app.use(bodyParser.json())

• It is a library, to install it run app.listen(3001)

this command “npm install


body-parser”
Hashing Passwords

• Whenever any user register in your website then they provide their email Id
and password, or any other type of information which can not be disclosed.
Then these type of information when getting saved in database it should be
hashed.
• Mostly will be hashing the passwords when user logs in.
• To do this complete procedure you can use this library named “bcrypt”.
• To install this library you can use the command : npm install bcrypt
bcrypt, first step - generate salt
const express = require("express");
To hash the password using bcrypt library const app = express();
you need to follow few steps like : const bcrypt = require("bcrypt");

• You have to first generate the salt, const saltRounds = 10;

this can be achieved by using app.get('/', function(req, res){


bcrypt.genSalt function bcrypt.genSalt(saltRounds, function(err, salt){

• This function takes two parameters if (err) console.log(err);


else {
one is salt rounds another is the console.log(salt);
callback function, this callback }
})
function returns the salt.
})
• This salt values again gets used to
hash the password app.listen(3001)
rypt, second step - generate hashed
const express = require("express");
password
const app = express();
const bcrypt = require("bcrypt");
• In this step to hash the
const saltRounds = 10;
password we will be using the Const pswd = “Student123@“;

function bcrypt.hash
app.get('/', function(req, res){
• This function takes three
bcrypt.genSalt(saltRounds, function(err, salt){
What is the for-in loop in JavaScript? Give its syntax

parameter, first is the password if (err) console.log(err);


else {
that is required to be hashed,
bcrypt.hash(pswd, salt, function(err, hashPswd){
next is the salt that we console.log(hashPswd)
generated in last step, and third }
}
is the callback function which
})
returns the hashed password. })

app.listen(3001)
bcrypt - hashing password

Now instead of doing it in two different steps, we can also combine these two steps
to create hashed password.
const express = require("express");
const app = express();
const bcrypt = require("bcrypt");
const saltRounds = 10; What is the for-in loop in JavaScript? Give its syntax

const pswd = "Student123@";

app.get('/', function(req, res){


bcrypt.hash(pswd, saltRounds, function(err, hashPswd){
if(err) console.log(err);
else console.log(hashPswd);
})
})
Exercise : 5

Create a backend application in which you can create variables like username and
password = “Prepbytes@$4321”. Now hash the password when we are redirecting on
route /register
Authentication & Authorization

Authentication and Authorization both are mainly used for security purposes of an
API. But the difference between these two things is that :

1.Authentication : When we are talking about authentication then we say that if a


person is providing his credential we will be checking if his credentials are correct
or not or if he is already an existing user or not
2.Authorization : When we are talking about authorization then we check that the
user who has logged is having access for this specific data or not. For example,
an Uber driver can not book the cab from the same account with which he has
logged in Uber application as driver.
JWT Tokens
• To achieve authentication in the APIs, we use JWT tokens.
• They stand for JSON Web Tokens.
• When any user logs-in by giving its username and password, then we will receive
the username and password in the request body of the API.
• Then using username and password we will create one token and assign it to the
user.
• Then whenever this user will be calling any API, then this token will be passed
from front-end application, then from backend application we will verify this token
is valid or not.
• This is how we can achieve authentication in the APIs using JWT tokens
JWT Tokens : Creation of Token
const express = require("express");
const jwt = require("jsonwebtoken");

• The first step is to install the library const app = express();


const pswd = "Student123@";
which we will use to create the token
const username = "John"
i.e. jsonwebtoken.
• Now we will use the function .sign const SECRET_KEY = "qwertyupoiuytrewq";

from jsonwebtoken which takes in two


app.post('/login', (req, res)=>{
params one is the obj for which we const user = {

are creating the token, another is the name: username,


pswd : pswd
secret key. This secret key is very
}
important as it will be used while const value = jwt.sign(user, SECRET_KEY);

verifying the user. res.send(value)


})
app.listen(3001);
WT Tokens : Verification of Token

• Whenever we will be passing this json app.get('/posts', function(req, res){

web token in any API, then we will be const value = req.headers("authorization");


const token = value && value.split(" ")[1];
passing it in the “Authorization” field
var decoded = jwt.verify(token, SECRET_KEY);
of headers of request body. res.json(decoded);
• Its structure is like : })

Authorization : Bearer —-token—- GET http://localhost:3001/posts


Authorization: Bearer
• Here we will be using verify function
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiIsInBzd2Qi
which takes token from request body OiJTdHVkZW50MTIzQCIsImlhdCI6MTYzOTA2NDM4NH0.pqLZaoRf-
AFdSwU4FpuFcfzrfhb7ZJ-ASF6WxlOzvc4
and that same secret key, it returns
the user obj, if the token is correct.
Exercise : 6

Create an API /user which accepts username and password. Then in response it
provides the token. Another API /courses which will receive the token first and verify it
and based on that it will pass the json of courses list.
Passport.js
Socket Programming
What is socket programming?
• If you have noticed that we always make API call or request only from client-side,
which means only communication can happen only from client-side. If server wants
to make some communication with the client, so it is not possible by creating
RESTful APIs.
• To achieve this concept that server should also be able to communicate the
message to client-side based on any event occurrence, we use Socket
Programming.
• We call it socket programming because in this we make a continuous connection
between client and server using “Sockets”.
t is one endpoint of a two-way communication link between two programs running on the
socket is bound to a port number so that the TCP layer can identify the application that d
is destined to be sent to.
ocket Implemention : Backend
const express = require("express");
const app = express();
• First we will have to install socket.io const socket = require("socket.io");

library in backend application


const server = app.listen(3001, ()=>{
• Then io variable is the socket that we
console.log("working");
have created in the backend. })

• Now this socket will have different const io = socket(server,{


cors : {
different events like “connection”,
origin : "*"
“disconnect”. So here I have written }
})
that if someone will connect means
connection event occurs then we will
io.on("connection",(socketClient)=>{
log something. console.log(“User connected”);
})
ocket Implemention : Frontend import React from "react";
import {io} from “socket.io-client"

class App extends React.Component{


• First we will have to install socket.io-
client library in client side application constructor(){
super();
this.socket = io("http://localhost:3001")
• Then in constructor we are trying to
}
connect with the server running on
port 3001. render(){
return(
<div>Hello</div>
• When we will start this application we )

will see that log statement in backend }

server terminal.
}
ocket Implemention : Chat App
Back-end Front-end

io.on('connection', (socket) => {


handleSubmit = ()=>{
socket.on('chat message', (msg) => {
var socket = io("http://localhost:3001");
console.log('message: ' + msg);
socket.emit('chat message’,”Some Message”);
});
}
});
Exercise : 7

Create a basic chat application using socket.

You might also like