7HTTP Methods Express
7HTTP Methods Express
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:
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)
• 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.
res.send('ab?cd')
})
This route path will match abcd, abbcd, abbbcd, and so on.
res.send('ab+cd')
})
This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so on.
res.send('ab*cd')
16
})
ExpressJS - Routing
});
17
Routers [main.js and routings.js]
});
18
Routers
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]
});
app.listen(3000);
Another Example
});
app.listen(8000);
21