Nodejs Express Framework
* * *\n\n## Express Introduction\n\nExpress is a concise and flexible Node.js web application framework that provides a series of powerful features to help you create various web applications and rich HTTP tools.\n\nUsing Express, you can quickly build a fully functional website.\n\nCore features of the Express framework:\n\n* Middleware can be set up to respond to HTTP requests.\n\n* A routing table is defined to execute different HTTP request actions.\n\n* HTML pages can be dynamically rendered by passing parameters to templates.\n\n* * *\n\n## Installing Express\n\nInstall Express and save it to the dependency list:\n\n$ cnpm install express --save\nThe above command will install the Express framework in the **node_modules** directory of the current directory, and an express directory will be automatically created under the **node_modules** directory. The following important modules need to be installed along with the express framework:\n\n* **body-parser** - Node.js middleware used to process JSON, Raw, Text, and URL-encoded data.\n\n* **cookie-parser** - This is a tool for parsing Cookies. You can retrieve the passed cookies through req.cookies and convert them into objects.\n\n* **multer** - Node.js middleware used to process form data with enctype="multipart/form-data" (setting the MIME encoding of the form).\n\n$ cnpm install body-parser --save $ cnpm install cookie-parser --save $ cnpm install multer --save\nAfter installation, we can check the version of express used:\n\n$ cnpm list express /data/www/node βββ express@4.15.2 -> /Users/tianqixin/www/node/node_modules/.4.15.2@express\n\n* * *\n\n## First Express Framework Example\n\nNext, we will use the Express framework to output "Hello World".\n\nIn the following example, we introduce the express module and respond with the "Hello World" string after the client makes a request.\n\nCreate the express_demo.js file with the following code:\n\n## express_demo.js file code:\n\nvar 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("Application Instance, Access Address at http://%s:%s", host, port)})\n\nExecute the above code:\n\n$ node express_demo.js Application Instance, Access Address at http://0.0.0.0:8081\nVisit http://127.0.0.1:8081 in your browser, the result is shown in the figure below:\n\n!(#)\n\n* * *\n\n## Request and Response\n\nExpress applications use the parameters of callback functions: **request** and **response** objects to handle request and response data.\n\napp.get('/', function (req, res) { // --})\nDetailed introduction to **request** and **response** objects:\n\n**Request Object** - The request object represents the HTTP request, containing properties such as the request query string, parameters, content, and HTTP headers. Common properties are:\n\n1. req.app: When the callback is an external file, use req.app to access the express instance\n2. req.baseUrl: Gets the URL path where the route is currently mounted\n3. req.body / req.cookies: Gets the "request body" / Cookies\n4. req.fresh / req.stale: Determines whether the request is still "fresh"\n5. req.hostname / req.ip: Gets the hostname and IP address\n6. req.originalUrl: Gets the original request URL\n7. req.params: Gets the route parameters\n8. req.path: Gets the request path\n9. req.protocol: Gets the protocol type\n10. req.query: Gets the URL query parameter string\n11. req.route: Gets the currently matched route\n12. req.subdomains: Gets the subdomains\n13. req.accepts(): Checks the acceptable document types for the request\n14. req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages: Returns the first acceptable character encoding of the specified character set\n15. req.get(): Gets the specified HTTP request header\n16. req.is(): Determines the MIME type of the request header Content-Type\n\n**Response Object** - The response object represents the HTTP response, i.e., the HTTP response data sent to the client when a request is received. Common properties are:\n\n1. res.app: Same as req.app\n2. res.append(): Appends the specified HTTP header\n3. res.set() will reset previously set headers after res.append()\n4. res.cookie(name, value [, option]): Sets a Cookie\n5. option: domain / expires / httpOnly / maxAge / path / secure / signed\n6. res.clearCookie(): Clears a Cookie\n7. res.download(): Transmits the file at the specified path\n8. res.get(): Returns the specified HTTP header\n9. res.json(): Transmits a JSON response\n10. res.jsonp(): Transmits a JSONP response\n11. res.location(): Only sets the response's Location HTTP header, does not set the status code or close the response\n12. res.redirect(): Sets the response's Location HTTP header and sets the status code to 302\n13. res.render(view,,callback): Renders a view, while passing the rendered string to the callback. If an error occurs during rendering, next(err) will be called automatically. The callback will be passed a possible error and the rendered page, so it will not be output automatically.\n14. res.send(): Transmits an HTTP response\n15. res.sendFile(path [, options] [, fn]): Transmits the file at the specified path - automatically sets Content-Type based on the file extension\n16. res.set(): Sets HTTP headers, passing an object can set multiple headers at once\n17. res.status(): Sets the HTTP status code\n18. res.type(): Sets the MIME type of Content-Type\n\n* * *\n\n## Routing\n\nWe have already understood the basic application of HTTP requests, and routing determines who (which specified script) responds to client requests.\n\nIn HTTP requests, we can extract the requested URL and GET/POST parameters through routing.\n\nNext, we will expand Hello World and add some features to handle more types of HTTP requests.\n\nCreate the express_demo2.js file with the following code:\n\n## express_demo2.js file code:\n\nvar express = require('express'); var app = express(); app.get('/', function(req, res){console.log("Homepage GET Request"); res.send('Hello GET'); })app.post('/', function(req, res){console.log("Homepage POST Request"); res.send('Hello POST'); })app.get('/del_user', function(req, res){console.log("/del_user Respond to DELETE Request"); res.send('Delete Page'); })app.get('/list_user', function(req, res){console.log("/list_user GET Request"); res.send('User List Page'); })app.get('/ab*cd', function(req, res){console.log("/ab*cd GET Request"); res.send('Regex Match'); })var server = app.listen(8081, function(){var host = server.address().address var port = server.address().port console.log("Application Instance, Access Address at http://%s:%s", host, port)})\n\nExecute the above code:\n\n$ node express_demo2.js Application Instance, Access Address at http://0.0.0.0:8081\nNext, you can try to access different addresses at http://127.0.0.1:8081 to see the effects.\n\nVisit http://127.0.0.1:8081/list_user in your browser, the result is shown in the figure below:\n\n!(#)\n\nVisit http://127.0.0.1:8081/abcd in your browser, the result is shown in the figure below:\n\n!(#)\n\nVisit http://127.0.0.1:8081/abcdefg in your browser, the result is shown in the figure below:\n\n!(#)\n\n* * *\n\n## Static Files\n\nExpress provides built-in middleware **express.static** to set up static files such as images, CSS, JavaScript, etc.\n\nYou can use the **express.static** middleware to set the static file path. For example, if you put images, CSS, and JavaScript files in the public directory, you can write:\n\napp.use('/public', express.static('public'));\nWe can put some images in the public/images directory, as shown below:\n\nnode_modules server.js public/public/images public/images/logo.png\nLet's modify the "Hello World" application again to add the functionality of handling static files.\n\nCreate the express_demo3.js file with the following code:\n\n## express_demo3.js file code:\n\nvar express = require('express'); var app = express(); app.use('/public', 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("Application Instance, Access Address at http://%s:%s", host, port)})\n\nExecute the above code:\n\n$ node express_demo3.js Application Instance, Access Address at http://0.0.0.0:8081\nExecute the above code:\n\nVisit http://127.0.0.1:80
YouTip