0% found this document useful (0 votes)
8 views

7HTTP Methods Express

Uploaded by

himanshisaini47
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

7HTTP Methods Express

Uploaded by

himanshisaini47
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Http Methods

GET
• GET request is used to get data from server.
• By default, when we enter URL in a browser, then browser creates a
get request for server .
• Example, if I write facebook.com, then a get request is generated.
• When server receives a GET request, it reads data from the database
and sends it to the client.

1
POST
• To send some data to a server
• Example: While filling up a form/signing in/creating an account, data
is submitted to server for storage/insertion in database.
• When server receives a POST request, it inserts the accompanying
data to the database.
• Every route may have 5 HTTP methods
GET,POST,PUT,PATCH,DELETE
• Example httpmethods.js
const log=`${req.method} $
{req.url}:Dataappended\n`;

2
• PUT Method
• Updates the database with an entirely new entry or
replaces the previous resource with a new one.
• Used for creating a new resource or replacing an existing
resource entirely.
• PATCH Method
• Partially updates an existing resource.
• Used when only specific parts of a resource need to be
modified, rather than replacing the entire resource.
• DELETE Method
• Removes an existing resource from the server.
• Used to delete a resource identified by the given URI.
3
const http=require("http");
const fs=require("fs");
const url=require("url");
const myServer=http.createServer((req,res)=>{
if(req.url==="/favicon.ico") return res.end();
const log=`${req.method} ${req.url}: Data appended\n`;
const myurl=url.parse(req.url);

fs.appendFile("log.txt",log,(err)=>{
if(err) throw err;

});

4
switch(myurl.pathname)
{
case '/':
if(req.method=='GET')
res.end("Hello, This is home page!!"); break;
case '/att':
res.end("Att complete");break;
case '/result':
res.end("Good result");break;
case '/signup':
if(req.method=='GET')
res.end("Form signup");
else if(req.method=='POST')
{
res.end("Success");
}
break;
default:
res.end("Not found");
}
}); 5
EXPRESS FRAMEWORK
Problems in myHandler() function:

• In previous program, we are making a route for each case.


• For each route, the http methods are being handled differently.
• Different modules like url, header are required to handle different
things
• Everything is being done from scratch.
Express can provide solution to all the above mentioned problems.

6
• To install, write npm i express.
• ‘Express’ will now be visible in dependencies of package.json.
• Now in code(expressprogs.js), write code
const express=require(“express”);
• Now write code
const app=express();
This code will initialize the app to express and it will act as a
myHandler() function now.
• Now, to tell, that for which request and path we need a handler, write
code:

7
const express=require("express");
const app=express();
app.get('/',(req,res)=>{
return res.send("Home Page from express");
})
app.get('/result',(req,res)=>{
return res.send(`Result Page from express ${req.query.name}`);
(((http://localhost:8000/result?name=sameera)))
})
app.listen(8000,()=>console.log("Your Server is
working"));

8
Express Overview
• Node.js web application framework with robust features
for web and mobile applications.
• open source framework developed and maintained by
the Node.js foundation.
• provides simple API to build websites, web apps and
back ends.
• With ExpressJS, no need to worry about low level
protocols, processes, etc.
• flexible as there are numerous modules available
on npm, which can be directly plugged into Express.

9
Environment
• First, install node and npm
• Confirm that node and npm are installed by running the following
commands in terminal
node
npm
• Brief recap of npm
npm is the package manager for node. The npm registry is a public
collection of packages for Node.js, front-end web apps, mobile apps etc.
npm allows to access all these packages and install them.
There are two ways to install a package using npm: globally and locally.
Globally : npm install -g <package-name>
Locally: A locally installed package can be used only within the directory
it is installed
npm install <package-name>
10
node --version npm --version

Environment
• After initializing npm, we have package.json file set up
• Now, further install Express.
• To install Express and add it to package.json file, use the
following command −
npm install express
• After setting up the environment, we develop first app using
Express:
var express = require('express’);
var app = express();
app.get('/', function(req, res){
res.send("Hello world!");
});
11
app.listen(3000);
Program explanation
• The first line imports Express in our file
• we have access to it through the variable express.
• We use it to create an application and assign it to var app
• app.get(route, callback)
This function tells what to do when a get request at the
given route is called.
The callback function has 2
parameters, request(req) and response(res).
The request object(req) represents the HTTP request.
The response object represents the HTTP response that the
Express app sends when it receives an HTTP request.
12
Program explanation
• res.send(): This function takes an object as input and it
sends this to the requesting client. Here we are sending
the string "Hello World!
• app.listen(port): This function binds and listens for
connections on the specified port.Port is a port number
where server should accept incoming requests.

13
ExpressJS – Routing (Routes and Methods)

Routing refers to determining how an application responds to a client


request
to a particular endpoint(or path) and a specific HTTP request method
(GET, POST, and so on).
Web frameworks provide resources such as HTML pages, scripts, images,
etc. at different routes.
Each route can have one or more handler functions, which are executed
when
the route is matched.
Route definition takes the following structure:
app.METHOD(PATH, HANDLER)
Ex: app.get(‘/att’,(err,……..))
Where:
•app is an instance of express.
•METHOD is an HTTP request method, in lowercase.
•PATH is a path on the server. 14
ExpressJS – Routing (Routes and Methods)

• Examples:
app.get('/result',(req,res)=>{
return res.send(“Hello”);
})
app.post(‘/att',(req,res)=>{
return res.send(“Attendance complete”);
})

15
route paths based on string patterns
This route path will match acd and abcd.

app.get('/ab?cd', (req, res) => {

res.send('ab?cd')

})

This route path will match abcd, abbcd, abbbcd, and so on.

app.get('/ab+cd', (req, res) => {

res.send('ab+cd')

})

This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so on.

app.get('/ab*cd', (req, res) => {

res.send('ab*cd')
16
})
ExpressJS - Routing

A special method, all, is provided by Express to handle


all types of http methods at a particular route using the
same function
app.all('/test', function(req, res){

res.send("HTTP method doesn't have any effect on this route!");

});

17
Routers [main.js and routings.js]

• Defining routes as in previous slides is very tedious to


maintain.
• To separate the routes from the main file,
use Express.Router. Create a new file ‘routings.js’ and
type the following code in it.
var express = require('express');

var router = express.Router();

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

res.send('GET route on routings.');

});

module.exports = router; //export this router to use in main file

18
Routers

Now to use this router in main file, type in the


following code in main file:
var express = require('Express');

var app = express();

var routings = require(‘./routings.js');

app.use(‘/routings’, routings);

app.listen(3000);

The app.use function call on route '/routings' attaches the routings router with this route. Now whatever
requests our app gets at the '/routings', will be handled by routings.js router

19
Dynamic routes [Dynrouting.js]

To use the dynamic routes, we must provide different


types of routes.
Dynamic routes allows us to pass parameters and do
processing based on them. Example:
var express = require('express');

var app = express();

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

res.send('The name you specified is ' + req.params.name);

});

app.listen(3000);

For output, type http://localhost:8000/sameera on browser


20
Dynamic routes [Dynrouting1.js]

Another Example

var express = require('express');

var app = express();

app.get('/routings/:name/:id', function(req, res) {

res.send('id: ' + req.params.id + ' and name: ' + req.params.name);

});

app.listen(8000);

21

You might also like