Express Framework in Node.js
Introducing Express Framework
Express is a small framework and utility for building web applications, providing a huge amount of powerful features for developing web and mobile applications. It is easy to develop fast applications based on Node.js for Web applications. Below are the basic features of Express framework.
Allow to set up intermediate classes to return HTTP requests.
The routing table definition can be used with different actions based on HTTP method and URL.
Allow returning HTML pages based on input parameters to the template.
Install Express Framework
First, installing Express framework using npm is as follows:
$ npm install express --save
The above command saves the installation in the node_modules directory and creates the express folder within that directory. Below are the important module components installed with express:
body-parser - This is an intermediate node node.js for handling JSON, raw data, text and URL encoding.
cookie-parser - Convert Cookie header and distribution to req.cookies
multer - This is an intermediate component in node.js to handle the multipart / form-data section.
$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save
Helloworld application example in Node.js
Here is a very basic example of Express that illustrates how to turn on the Server and listen to connections on port 3000. This application returns Hello World! for requests to the homepage. For other paths, it will return a 404 Not Found.
Create server.js with the following content:
var express = require ( 'express' ); var app = express (); app . get ( '/' , function ( req , res ) { res . send ( 'Hello World' ); }) var server = app . listen ( 8081 , function () { var host = server . address (). address var port = server . address (). port console . log ( "Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s" , host , port ) })
Run server.js to see the result.
$ node server.js
You will see the results appear:
Cavalier Node.js is listening to the ear: http://0.0.0.0:8081
Open http://127.0.0.1:8081/ in any browser and see the results.
Request & Response object in Node.js
Express application uses a callback function whose parameters are request and response objects.
app . get ( '/' , function ( req , res ) { // -- })
You can refer to the details of these two objects below:
- Request object - This object represents an HTTP request and has properties for requests such as query strings, parameters, body, HTTP headers and others.
- Response object - This object represents the HTTP response sent by the Express application when it receives an HTTP request.
You can print req and res objects to provide a large amount of information related to HTTP requests and return cookies, sessions, URLs .
Basic routing
Above, you have just watched a basic application that the HTTP Server requests to a home page. Routing involves identifying an application that returns a Client Request to a specific Endpoint, which is a URI path and returns an HTTP request (GET, POST and other methods).
Based on the above Hello World program, I will develop some additional functions to handle HTTP requests.
var express = require ( 'express' ); var app = express (); // Phuong thuc get() phan hoi mot GET Request ve Homepage app . get ( '/' , function ( req , res ) { console . log ( "Nhan mot GET Request ve Homepage" ); res . send ( 'Hello GET' ); }) // Phuong thuc post() phan hoi mot POST Request ve Homepage app . post ( '/' , function ( req , res ) { console . log ( "Nhan mot POST Request ve Homepage" ); res . send ( 'Hello POST' ); }) // Phuong thuc delete() phan hoi mot DELETE Request ve /del_user page. app . delete ( '/del_user' , function ( req , res ) { console . log ( "Nhan mot DELETE Request ve /del_user" ); res . send ( 'Hello DELETE' ); }) // Phuong thuc nay phan hoi mot GET Request ve /list_user page. app . get ( '/list_user' , function ( req , res ) { console . log ( "Nhan mot GET Request ve /list_user" ); res . send ( 'Page Listing' ); }) // Phuong thuc nay phan hoi mot GET Request ve abcd, abxcd, ab123cd, . app . get ( '/ab*cd' , function ( req , res ) { console . log ( "Nhan mot GET request ve /ab*cd" ); res . send ( 'Page Pattern Match' ); }) var server = app . listen ( 8081 , function () { var host = server . address (). address var port = server . address (). port console . log ( "Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s" , host , port ) })
Save the code in server.js and run this file with the following command:
$ node server.js
Check the result:
Cavalier Node.js is listening to the ear: http://0.0.0.0:8081
Now, you can try other Requests at http://127.0.0.1:8081 to see the results created by server.js. Here are some screens showing different responses with different URLs.
Screen results for http://127.0.0.1:8081/list_user
Screen results for http://127.0.0.1:8081/abcd
Screen results for http://127.0.0.1:8081/abcdefg
For static files
Express provides express.static middleware utilities to serve static files like images, CSS, Javascript, .
Basically, you just need to pass the directory name where you keep these files, express.static will use that file directly. For example, if you want to keep images, CSS and Javascript in the public directory, you can do the following:
app . use ( express . static ( 'public' ));
Suppose I keep some images in the subdirectory public / images as follows:
node_modules
server.js
public /
public / images
public / images / logo.png
Modify the "Hello Word" application to add some additional features to handle static files:
var express = require ( 'express' ); var app = express (); app . use ( express . static ( 'public' )); app . get ( '/' , function ( req , res ) { res . send ( 'Hello World' ); }) var server = app . listen ( 8081 , function () { var host = server . address (). address var port = server . address (). port console . log ( "Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s" , host , port ) })
Save the code in server.js and run this file with the following command:
$ node server.js
Now open the browser and type the address http://127.0.0.1:8081/images/logo.png to see the result.
Example GET method
Here is a simple example to pass two values using the HTML FORM with the GET method. I will use process_get in server.js to handle the input.
Save the above code in index.htm and modify server.js as follows.
var express = require ( 'express' ); var app = express (); app . use ( express . static ( 'public' )); app . get ( '/index.htm' , function ( req , res ) { res . sendFile ( __dirname + "/" + "index.htm" ); }) app . get ( '/process_get' , function ( req , res ) { // Chuan bi output trong dinh dang JSON response = { first_name : req . query . first_name , last_name : req . query . last_name }; console . log ( response ); res . end ( JSON . stringify ( response )); }) var server = app . listen ( 8081 , function () { var host = server . address (). address var port = server . address (). port console . log ( "Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s" , host , port ) })
Open the browser and type the address http://127.0.0.1:8081/index.htm to see the result:
{ "first_name" : "Hoang" , "last_name" : "Nguyen Manh" }
Example POST method
Below is a basic example to pass two values using HTML form using POST method. I will use process_post in server.js to handle this input.
Save the above code in index.htm and modify server.js as follows:
var express = require ( 'express' ); var app = express (); var bodyParser = require ( 'body-parser' ); // Tao mot parser co dang application/x-www-form-urlencoded var urlencodedParser = bodyParser . urlencoded ({ extended : false }) app . use ( express . static ( 'public' )); app . get ( '/index.htm' , function ( req , res ) { res . sendFile ( __dirname + "/" + "index.htm" ); }) app . post ( '/process_post' , urlencodedParser , function ( req , res ) { // Chuan bi output trong dinh dang JSON response = { first_name : req . body . first_name , last_name : req . body . last_name }; console . log ( response ); res . end ( JSON . stringify ( response )); }) var server = app . listen ( 8081 , function () { var host = server . address (). address var port = server . address (). port console . log ( "Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s" , host , port ) })
Open the browser and type the address http://127.0.0.1:8081/index.htm to see the result:
{ "first_name" : "Hoang" , "last_name" : "Nguyen Manh" }
For example File Upload
Here is HTML code to create a File Upload Form. This form has properties set to POST method and encryption attribute to set multipart / form-data .
File Uploading Form
File Upload: Select a file to upload:
/>
Save the above code in index.htm and modify server.js as follows:
var express = require ( 'express' ); var app = express (); var fs = require ( "fs" ); var bodyParser = require ( 'body-parser' ); var multer = require ( 'multer' ); app . use ( express . static ( 'public' )); app . use ( bodyParser . urlencoded ({ extended : false })); app . use ( multer ({ dest : '/tmp/' })); app . get ( '/index.htm' , function ( req , res ) { res . sendFile ( __dirname + "/" + "index.htm" ); }) app . post ( '/file_upload' , function ( req , res ) { console . log ( req . files . file . name ); console . log ( req . files . file . path ); console . log ( req . files . file . type ); var file = __dirname + "/" + req . files . file . name ; fs . readFile ( req . files . file . path , function ( err , data ) { fs . writeFile ( file , data , function ( err ) { if ( err ){ console . log ( err ); } else { response = { message : 'File duoc upload thanh cong!' , filename : req . files . file . name }; } console . log ( response ); res . end ( JSON . stringify ( response ) ); }); }); }) var server = app . listen ( 8081 , function () { var host = server . address (). address var port = server . address (). port console . log ( "Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s" , host , port ) })
Now open the browser and type the address http://127.0.0.1:8081/index.htm to see the result:
Example of Cookie management
You can send Cookies to Node.js Server. The following example illustrates how to print all Cookies sent by the Client.
var express = require ( 'express' ) var cookieParser = require ( 'cookie-parser' ) var app = express () app . use ( cookieParser ()) app . get ( '/' , function ( req , res ) { console . log ( "Cookies: " , req . cookies ) }) app . listen ( 8081 )
According to Tutorialspoint
Previous article: Web Module in Node.js
Next article: RESTful API in Node.js
You should read it
- TOP 10 best Web Framework, most worth using
- Effective Microsoft .NET Framework repair and removal tool
- What is the Microsoft .NET Framework, and why is it installed on the PC?
- How to fix Microsoft .NET Framework 4 installation error 0x800c0006 on Windows
- Fix the error of not installing the .NET Framework 3.5 on Windows
- How to install Microsoft NET Framework 4.5 full for Windows 7, 8 with Windows Update
- How to enable .NET FrameWork on Windows 10?
- Fix error 0x800F081F when installing .Net Framework 3.5
May be interested
- Top 5 popular CSS Framework that you should keep in mindtoday's css frameworks are becoming more popular and it's hard to imagine a website that doesn't use css framework.
- TOP 10 best Web Framework, most worth usingwhat is web framework? which web framework should i use? introducing to you the top 10 best web frameworks today that you should know
- How to activate .Net Framework 3.5 on Windows 10how to enable .net framework 3.5 on win10. some old software still works and requires .net framework 3.5 and you have to do the following to re-enable .net framework 3.5 on windows 10.
- What would users like to change on Adobe Express Mobile?people often use adobe express mobile to create cool visual designs from their phones, but it lacks one key feature compared to the adobe express desktop browser tool.
- Microsoft warns many versions of .NET Framework will expire in Aprilmicrosoft has just moved to remind users and customers that many versions of the .net framework signed with an insecure hash algorithm (sha-1) will expire at the end of april 2022.
- Microsoft announced the death of many old versions of .NET Frameworkmicrosoft has officially announced that a series of versions of the .net framework using the legacy and insecure secure hash algorithm 1 (sha-1) will enter the end of support. (death) in 2022.
- What is the Microsoft .NET Framework? Why do I need to install .Net Framework on my computer?what is the microsoft .net framework? why is .net framework installed on the computer ?. when we install the software on our computer, we will encounter some cases that require the computer to have the .net framework to run. so what is the .net framework, at
- Instructions for installing .NET Framework 3.5 Offline on Windows 10windows 10 is installed with .net framework 4.5. however, many applications developed from windows vista and windows 7 require the .net framework v3.5 version installed with the .net framework version 4.5.
- How to check .NET Framework version on Windows 10some software requires you to install the appropriate version of the .net framework to run, here are the two simplest and most common ways to check the .net framework version.
- Download Net Framework 4.5 full Online - Offlinemicrosoft .net framework 4.5.2 full is a programming platform that supports the use and installation of software on personal computers. net framework 4.5.2 is a new upgraded version with many features that support many software on the system, helping your operating system operate more stably and securely.