Node
Node
Node
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.
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
• With a myriad of HTTP utility methods and middleware at your disposal, creating a
robust API is quick and easy.
• 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.listen(3001)
Exercise : 2
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
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();
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();
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
• 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
• 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();
app.listen(3001)
Express : Query Params
const express = require("express");
const app = express();
app.listen(3001)
Exercise : 5
• 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
• 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");
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
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
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 :
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");
server terminal.
}
ocket Implemention : Chat App
Back-end Front-end