Lec5_ExpressJS2_student PDF

Summary

This document is a lecture on ExpressJS, a web application framework for Node.js. It covers topics such as working with forms, uploading files, and handling cookies and sessions. It also includes examples of creating and handling form data, using Multer for file uploads, and setting and managing cookies using cookie and session modules.

Full Transcript

Lecture 5 ExpressJS (part 2) EIE4432 WEB SYSTEMS AND TECHNOLOGIES Dr. Pauli Lai 1 Expected learning outcomes After this lecture, you should understand … ▪ How to receive upload file with multer ▪ Handling cookie/session with express-session 2 ExpressJS - Form data Forms are an integral part...

Lecture 5 ExpressJS (part 2) EIE4432 WEB SYSTEMS AND TECHNOLOGIES Dr. Pauli Lai 1 Expected learning outcomes After this lecture, you should understand … ▪ How to receive upload file with multer ▪ Handling cookie/session with express-session 2 ExpressJS - Form data Forms are an integral part of the web. Almost every website we visit offers us forms that submit or fetch some information for us. To get started with forms, we will first install the body-parser (for parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middlewares. To install the body-parser and multer, go to your terminal and use: npm install --save body-parser multer References: http://expressjs.com/en/resources/middleware/body-parser.html http://expressjs.com/en/resources/middleware/multer.html 3 ExpressJS - Form data Create your form.html file contents with the following code and put it under /public folder. <html> <head> <title>Form Tester</title> </head> <body> <form action="/" method="POST"> <div> <label for="say">Say:</label> <input name="say" value="Hi"> </div> <br> <div> <label for="to">To:</label> <input name="to" value="Express forms"> </div> <br> <button type="submit">Send my greetings</button> </form> </body> </html> 4 ExpressJS - Form data Create your form.js file contents with the following code import express from 'express'; import bodyParser from 'body-parser'; import multer from 'multer'; const upload = multer(); const app = express(); app.get('/', (req, res) => { res.redirect('form.html'); }); // for parsing application/json // not used here app.use(bodyParser.json()); // for parsing application/xwww-form-urlencoded app.use(bodyParser.urlencoded({ extended: true })); // for parsing multipart/form-data // accept text fields only app.use(upload.none()); // serving static files from public folder app.use(express.static('public')); app.post('/', (req, res) => { console.log(req.body); res.send("recieved your request!"); }); app.listen(3000); After importing the body parser and multer, we will use the body-parser for parsing json and xwww-form-urlencoded header requests, while we will use multer for parsing multipart/form-data. 5 Result Run your server using the following. node form.js or nodemon form.js Now go to localhost:3000/; it will be redirected to /form.html Fill out the form as you like and submit it. The following response will be displayed − Have a look at your console; it will show you the body of your request as a JavaScript object as in the following screenshot − 6 ExpressJS – Upload Files Multer is a express.js middleware for handling multipart/form-data request, which is primarily used for uploading files. This example save the received files to ./upload/file/path import multer form 'multer'; const upload = multer({ dest: './upload/file/path' }); … app.post('/profile', upload.any(), (req, res) => { // Upload file information will be available at req.files … } HTML upload form <form action="/profile" method="post" enctype="multipart/form-data"> <input type="file" name="upload" /><br> <button type="submit">Upload file</button> </form> Note that upload.any() must be placed before the user handlers, and an array of files will be stored in req.files. Other types of fields will be stored in req.body as usual. Notes: upload.any() accepts any number of files 7 Express.js: Receive Files The available field of each File in req.files: 8 ExpressJS – Upload Files Create your form_upload.html file contents with the following code and put it under /public folder. <html> <head> <title>Form Upload Tester</title> </head> <body> <form action="/profile" method="post" enctype="multipart/form-data"> <input type="file" name="upload" /><br> <button type="submit">Upload file</button> </form> </body> </html> 9 ExpressJS – Upload Files Create your form_upload.js file contents with the following code import express from 'express'; import multer from 'multer'; const upload = multer({ dest: './upload/file/path' }); var app = express(); app.get('/', (req, res) => { res.redirect('form_upload.html'); }); // serving static files from public folder app.use(express.static('public')); app.post('/profile', upload.any(), (req, res) => { // Upload file information will be available at req.files console.log(req.body); console.log(req.files); res.send("File uploaded!"); }); app.listen(3000); 10 Result Run your server using the following. node form_upload.js Now go to localhost:3000/; it will be redirected to /form_upload.html Select the file from your file system and click “Upload file” to submit. The following response will be displayed − 11 Result Have a look at your console; it will show you req.body as a null prototype, and req.files with different field values as in the following screenshot − You can find the uploaded file in the destination path with a temporary file name. 12 ExpressJS – Upload Files Modify the above program form_upload.js to change the temporary file name to the original file name. //const upload = multer({ dest: './upload/file/path' }); var storage = multer.diskStorage( { destination: './upload/file/path', filename: ( req, file, cb ) => { cb( null, Date.now() + '-' + file.originalname); } } ); var upload = multer( { storage: storage } ); 13 Knowledge Check (Fill in the blanks) Create your UploadFileMulter.js file contents with the following code import express from 'express'; import multer from 'multer'; const upload = multer({ dest: './uploaded' }); const app = express(); app.get('/', (req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<form action="/fileupload" method="post" enctype="multipart/form-data">'); res.write('<input type="file" name="filetoupload" <br>'); res.write('<input type="submit">'); res.write('</form>'); res.end(); }); app.post('/fileupload', upload.any(), (req, res) => { const file = req.files[0]; res.send(`File uploaded to ${file.path}`); res.end() }); app.listen(3000); Result 14 Knowledge Check (Fill in the blanks) The available field of each File in req.files: Example of uploading the "hello.txt" 15 ExpressJS – Upload Files Recall the file upload code with Formidable in the last lecture. Both code do the same task. import http from 'http'; import formidable from 'formidable'; http.createServer((req, res) => { if (req.url == '/fileupload') { const form = formidable({}); form.parse(req, (err, fields, files) => { const oldpath = files.filetoupload[0].filepath; res.write('File uploaded to ' + oldpath); res.end(); }); } else { res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<form action="fileupload" method="post" enctype="multipart/form-data">'); res.write('<input type="file" name="filetoupload"><br>'); res.write('<input type="submit">'); res.write('</form>'); res.end(); } }).listen(8080); Express.js with Multer is more readable and handier. POST /fileupload (Upload file) app.post('/fileupload', upload.any(), (req, res) => { const file = req.files[0]; res.send(`File uploaded to ${file.path}`); res.end(); }); app.listen(3000); GET / (Return the HTML form) app.get('/', (req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<form action="/fileupload" method="post" enctype="multipart/form-data">'); res.write('<input type="file" name="filetoupload" <br>'); res.write('<input type="submit">'); res.write('</form>'); res.end(); }); 16 ExpressJS - Cookies Cookies are simple, small files/data that are sent to the client with a server response and stored on the client side. Every time the user loads the website back, this cookie is sent to the server with the request. This helps us keep track of the user’s actions. The following are the numerous uses of the HTTP Cookies: • Session management • Personalization (Recommendation systems) • User tracking 17 ExpressJS - Cookies To use cookies with Express, we need the cookie-parser middleware. To install it, use the following code − npm install --save cookie-parser Now to use cookies with Express, we will import the cookie-parser. cookieparser is a middleware which parses cookies attached to the client request object. To use it, we will import it in our cookie.js file; this can be used the same way as we use other middleware. Here, we will use the following code. import cookieParser from 'cookie-parser'; app.use(cookieParser()); cookie-parser parses Cookie header and populates req.cookies with an object keyed by the cookie names. 18 ExpressJS - Cookies To set a new cookie, let us define a new route in your Express app like − import express from 'express'; const app = express(); app.get('/', (req, res) => { //Sets name = express res.cookie('name', 'express').send('cookie set’); }); app.listen(3000); 19 ExpressJS - Cookies The browser also sends back cookies every time it queries the server. To view cookies from your server, on the server console in a route, add the following code to that route. import express from 'express'; import cookieParser from 'cookie-parser'; const app = express(); app.use(cookieParser()); app.get('/', (req, res) => { //Sets name = express //res.cookie('name', 'express').send('cookie set'); console.log('Cookies: ', req.cookies); }); Next time you send a request to this route, you will receive the following output. app.listen(3000); 20 Adding Cookies with Expiration Time You can add cookies that expire. To add a cookie that expires, just pass an object with property 'expire' set to the time when you want it to expire. For example, //Expires after 360000 ms from the time it is set. res.cookie(name, 'value', {expire: 360000 + Date.now()}); Another way to set expiration time is using 'maxAge' property. Using this property, we can provide relative time instead of absolute time. Following is an example of this method. //This cookie also expires after 360000 ms from the time it is set. res.cookie(name, 'value', {maxAge: 360000}); 21 Deleting Existing Cookies To delete a cookie, use the clearCookie function. For example, if you need to clear a cookie named ’name’, use the following code. import express from 'express'; const app = express(); app.get('/clear_cookie_name', (req, res) => { res.clearCookie('name'); res.send('cookie name cleared'); }); app.listen(3000); 22 Express.js: Cookie/Session In Express.js, session management can be achieved by the express-session package. Server send the signed Session ID to the client as a cookie. Client send requests with this cookie to identify the current session. 23 ExpressJS - Sessions HTTP is stateless. In order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies and URL parameters are both suitable ways to transport data between the client and the server. But they are both readable and on the client side. Sessions solve exactly this problem. You assign the client an ID and it makes all further requests using that ID. Information associated with the client is stored on the server linked to this ID. We will need the express-session, so install it using the following code. npm install --save express-session 24 ExpressJS - Sessions In this example, we will use the default store for storing sessions, i.e., MemoryStore. Never use this in production environments. The session middleware handles all things for us, i.e., creating the session, setting the session cookie and creating the session object in req object. Whenever we make a request from the same client again, we will have their session information stored with us (given that the server was not restarted). We can add more properties to the session object. In the following example, we will create a view counter for a client. 25 ExpressJS - Sessions import express from 'express'; import session from 'express-session'; const app = express(); app.use(session({ secret: 'secret-to-sign-cookie', resave: false, saveUninitialized: false, cookie: { httpOnly: true, maxAge: 60000} })); After 60s app.get('/', (req, res) => { if(req.session.page_views){ req.session.page_views++; res.send("You visited this page " + req.session.page_views + " times"); } else { req.session.page_views = 1; res.send("Welcome to this page for the first time!"); } }); app.listen(3000); 26

Use Quizgecko on...
Browser
Browser