expreeupdated
expreeupdated
js TUTORIALS
INTRODUCTION OF EXPRESS.js
Examples:
req.accepts('html');
req.accepts('text/html');
EXPRESS.js REQUEST
Request Object Methods
METHODS
req.is(type)
This method returns true if the incoming request's
"Content-Type" HTTP header field matches the MIME
type specified by the type parameter.
Examples:
req.is('html');
req.is('text/html');
req.is('text/*');
EXPRESS.js REQUEST
Request Object Methods
METHODS
req.param(name [, defaultValue])
This method is used to fetch the value of param
name when present.
EXAMPLE
req.param('name')
EXPRESS.js RESPONSE
Express.js Response Object
OBJECTS
The Response object (res) specifies the HTTP response
which is sent by an Express app when it gets an HTTP
request.
It sends response back to the client browser.
It facilitates you to put new cookies value and that will
write to the client browser (under cross domain rule).
Once you res.send() or res.redirect() or res.render(), you
cannot do it again, otherwise, there will be uncaught error.
EXPRESS.js RESPONSE
PROPERTIES
Response Object Properties
res.app
res.headersSent
res.locals
app.get('/', function (req, res) {
console.dir(res.headersSent) // false
res.send('OK')
console.dir(res.headersSent) // true
})
EXPRESS.js RESPONSE
METHODS Response methods
res.append()
res.attachment()
res.cookie()
res.clearCookie()
res.download()
res.end()
res.format()
res.get()
res.json()
res.links()
res.redirect()
res.render()
res.send()
res.status()
res.type()
EXPRESS.js GET ,POST
REQUEST
GET and POST
GET and POST both are two common HTTP requests used for
building REST(representational state transfer architectural style)
API's. GET requests are used to send only limited amount of data
because data is sent into header while POST requests are used to
send large amount of data because data is sent in the body.
Express.js facilitates you to handle GET and POST requests using
the instance of express.
EXPRESS.js
Index.html POST REQUESTMain.js
<html>
Sample program
var express = require('express');
<body> var app = express();
var bodyParser = require('body-parser');
<form
// Create application/x-www-form-urlencoded parser
action="http://127.0.0.1:8000/process_post" var urlencodedParser = bodyParser.urlencoded({ extended: false })
method="POST"> app.use(express.static('public'));
First Name: <input type="text" app.get('/index.html', function (req, res) {
name="first_name"> <br> res.sendFile( __dirname + "/" + "index.html" );
Last Name: <input type="text" })
app.post('/process_post', urlencodedParser, function (req, res) {
name="last_name"> // Prepare output in JSON format
<input type="submit" value="Submit"> response = {
</form> first_name:req.body.first_name,
</body> last_name:req.body.last_name
</html> };
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
POST
Post method facilitates you to send large amount of data because
data is send in the body. Post method is secure because data is
not visible in URL bar but it is not used as popularly as GET
method. On the other hand GET method is more efficient and
used more than POST.
Let's take an example to demonstrate POST method.
1.<html>
2.<body>
3.<form action="http://127.0.0.1:8000/
process_post" method="POST">
4.First Name: <input type="text" name="first_name"> <br>
5.Last Name: <input type="text" name="last_name">
6.<input type="submit" value="Submit">
7.</form>
8.</body>
9.</html>
1.var express = require('express');
2.var app = express();
3.var bodyParser = require('body-parser');
4.// Create application/x-www-form-urlencoded parser
5.var urlencodedParser = bodyParser.urlencoded({ extended: false })
6.app.use(express.static('public'));
7.app.get('/index.html', function (req, res) {
8. res.sendFile( __dirname + "/" + "index.html" );
9.})
10.app.post('/process_post', urlencodedParser, function (req, res) {
11. // Prepare output in JSON format
12. response = {
13. first_name:req.body.first_name,
14. last_name:req.body.last_name
15. };
16. console.log(response);
17. res.end(JSON.stringify(response));
18.})
19.var server = app.listen(8000, function () {
20. var host = server.address().address
21. var port = server.address().port
22. console.log("Example app listening at http://%s:%s", host, port)
Express.js Routing
Routing is made from the word route. It is used to
determine the specific behavior of an application. It
specifies how an application responds to a client
request to a particular route, URL or path and a
specific HTTP request method (GET, POST, etc.). It
can handle different types of HTTP requests.
1.var express = require('express');
2.var app = express();
3.app.get('/', function (req, res) {
4. console.log("Got a GET request for the homepage");
5. res.send('Welcome to JavaTpoint!');
6.})
7.app.post('/', function (req, res) {
8. console.log("Got a POST request for the homepage");
9. res.send('I am Impossible! ');
10.})
11.app.delete('/del_student', function (req, res) {
12. console.log("Got a DELETE request for /del_student");
13. res.send('I am Deleted!');
14.})
1.app.get('/enrolled_student', function (req, res) {
2. console.log("Got a GET request for /enrolled_student");
3. res.send('I am an enrolled student.');
4.})
5.// This responds a GET request for abcd, abxcd, ab123cd,
and so on
6.app.get('/ab*cd', function(req, res) {
7. console.log("Got a GET request for /ab*cd");
8. res.send('Pattern Matched.');
9.})
10.var server = app.listen(8000, function () {
11.var host = server.address().address
12. var port = server.address().port
13.console.log("Example app listening at http://%s:
%s", host, port)
14.})
EXPRESS.js FILE
Express.js
UPLOAD File Upload and Download
File uploading and downloading are important features of
a web app. Here we are going to handle file upload
using express-fileupload npm package, and the download
is handled using res.download() function of the express.
The express-fileupload is passed to the app as the
middleware.
Approach: First, install express-fileupload module and
then require it and pass it as middleware to the app as
shown below:
const fileUpload = require('express-fileupload')
app.use(fileUpload())
Then in order to access the uploaded files inside POST request
using:
req.files.<uploaded_file_name>
It provides some functions and values such as file name, type,
data, and size. It provides an important mv() function which is
used to save the uploaded file. It takes the upload path and an
error handling function as parameters.
req.files.<uploaded_file_name>.mv(<upload_path>,
function(err) { // statement(s) })
EXPRESS.js
In Express.js,END
file upload is slightly difficult
because of its asynchronous nature and
networking approach.
It can be done by using middleware to
handle multipart/form data. There are
many middleware that can be used like
multer, connect, body-parser etc.
Let's take an example to demonstrate file upload in Node.js.
Here, we are using the middleware 'multer'.
Create a folder "jtp file upload" having the following files:
uploads: It is an empty folder i.e. created to store the
uploaded images.
package: It is JSON file, having the following data:
File: package.json has code
1.{
2. "name": "file_upload",
3. "version": "0.0.1",
4. "dependencies": {
5. "express": "4.13.3",
6. "multer": "1.1.0"
7. },
8. "devDependencies": {
9. "should": "~7.1.0",
10. "mocha": "~2.3.3",
11. "supertest": "~1.1.0"
12. }
13.}
File: index.html
1.<html>
2. <head>
3. <title>File upload in Node.js by CU</title>
4.
5. </head>
6. <body>
7. <h1>Express.js File Upload: by CU</h1>
8. <form id="uploadForm" enctype="multipart/form-data" action="/
uploadCU" method="post">
9. <input type="file" name="myfile" /><br/><br/>
10. <input type="submit" value="Upload Image" name="submit"><br/
><br/>
11. <span id="status"></span>
12. </form>
13. </body>
14.</html>
5.var storage = multer.diskStorage({
6. destination: function (req, file, callback) {
7. callback(null, './uploads');
8. },
9. filename: function (req, file, callback) {
10. callback(null, file.originalname);
11. }
12.});
13.var upload = multer({ storage : storage}).single('myfile');
14.
15.app.get('/',function(req,res){
16. res.sendFile(__dirname + "/index.html");
17.});
18.
19.app.post('/uploadCU',function(req,res){
20. upload(req,res,function(err) {
21. if(err) {
22. return res.end("Error uploading file.");
23. }
24. res.end("File is uploaded successfully!");
25. });
How to Download a File using
Express.js ?
To download a file using express.js we are
going to see two scenarios:
1.Downloading a single file using res.download()
function which takes two parameters the path of the
file and a function to handle if any error occurs.
2.Downloading multiple files as a zipped folder for
this we would use the “express-zip” npm package
which creates a zipped folder using the zip() function
which takes an array of objects as a parameter. Each
object has two fields path and file name.
Steps to Implement File Download in Express
Step 1: Create an “app.js” file and initialize your project with npm.
npm init
Step 2: Now install two npm packages: “express” and “express-
zip“.
single_gfg.txt
multiple_one_gfg.txt
multiple_two_gfg.txt
multiple_three_gfg.txt
Step 4: Now let us code the “index.html” file. In it we
will create two forms:
•One with GET route as – ‘/single‘ (to handle the single
file download request).
•One with GET route as – ‘/multiple‘ (to handle the
multiple file download request).
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Download</title>
</head>
<body>
<br>
<!-- Form to handle single file download request-->
<form action="/single" method="get">
<button type="submit">Download Single File</button>
</form>
<br><br>
</body>
</html>
Step 5: Now code the “app.js” file. In it,
we create GET request functions to
handle the download requests using
express. We use “express-zip”
and res.download() as mentioned at the
start.
// filename - app.js
const express = require('express')
const app = express();
const folderPath = __dirname+'/Files';
app.get('/single',function(req,res) {
console.log('single file');
res.download(folderPath+'/single_gfg.txt', function(err) {
if(err) {
console.log(err);
}
})
})
app.get('/api/books/:id',
(req, res) => {
const id =
parseInt(req.params.id);
const book =
books.find(book => book.id === id);
if (book) {
res.json(book);
} else {
res.status(404)
.json({ message: 'Book not found' });
}
});
S.No. Git GitHub
1. Git is a software. GitHub is a service.
2. Git is a command-line tool GitHub is a graphical user interface