1. Trang chủ
  2. » Giáo án - Bài giảng

4 1 how express works tủ tài liệu training pdf

14 67 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 14
Dung lượng 68,82 KB

Nội dung

Express Framework Starting with Express.js Express.js is a web framework based on the core Node.js http module1 and Connect2 components Those components are called middleware They are the cornerstone of the framework’s philosophy, which is configuration over convention Some developers familiar with Ruby compare Express.js to Sinatra, which has a very different approach from the Ruby on Rails framework that favors convention over configuration In other words, developers are free to pick whatever libraries they need for a particular project This approach provides them with flexibility and the capability to highly customize their projects If you have written any serious apps using only the core Node.js modules, you most likely found yourself reinventing the wheel by constantly writing the same code for similar tasks, such as: Parsing HTTP request bodies Parsing cookies Managing sessions Organizing routes with a chain of if conditions based on URL paths and HTTP methods of the requests Determining proper response headers based on data types Handling errors Extracting URL parameter (e.g., /messages/3233) Starting with Express.js Later, you might have created your own libraries to reuse the code, but your libraries would not be as thoroughly tested as the best community supported libraries Also, the maintenance would be fully on you and your team So, my recommendation is to use the community module if it suites your needs This advice applies to using small libraries and web frameworks as well Express.js solves these and many other problems It provides ways to reuse code elegantly and provides a model-view-controller (MVC)-like structure for your web apps The model (M) part needs to be supplied by an additional database-driver library (e.g., Mongoose3 ) Those apps could vary from barebones, back-end-only REST APIs to full-blown, full-stack, real-time web apps with additional libraries such as jade-browser (https://npmjs.org/package/jade-browser) and socket.io (http://socket.io) To get you started with Express.js quickly and without diving too deep into its API, we’ll cover these topics in this chapter: ● ● ● How Express.js works Express.js installation Express.js Generator installation How Express.js Works Express.js is a node package manager (NPM or npm) module that is a dependency to your application This means that every project that is built with/on Express.js needs to have the framework’s source files in the local node_modules folder (not globally!) For this, you install Express.js just like any other NPM module, with $ npm install, e.g., $ npm install express@4.2.0 Now, we can overview a typical structure of an Express.js application Let’s say your application is in a server.js file and you plan to start your application with $ node server.js In that case, you need to require and configure Express.js in the server.js file This file usually contains statements to accomplish the following: ● ● ● ● ● ● ● Include third-party dependencies as well as your own modules such as controllers, utilities, helpers, and models Instantiations of the Express.js object and others Connect to databases such as MongoDB , Redis , or MySQL Configure Express.js app settings such as the template engine and its files’ extensions Define middleware such as error handlers, static files folder, cookies, and other parsers Define routes and their request handlers Start the app which will start the server on a particular host and port Of course, if your application is big, you’ll have multiple files to configure your Express.js app, not just a single server.js or app.js file The reason for that is better code organization For example, in one file you will configure sessions, in another authentication, in another routes, and so forth How Express.js Works Third-Party Dependencies Defining third-party dependencies is straightforward: var name = require('name'); The dependencies typically include the Express.js library itself, along with necessary middleware such as body-parser Another way to define multiple dependencies is to follow each definition with a comma: var express = require('express'), compression = require('compression'), bodyParser = require('body-parser'), mongo = require('mongoskin'); How Express.js Works Instantiations To use Express.js, you need to instantiate it At the same time, it’s a good practice to instantiate any other objects: var app = express(); var db = mongo.db('mongodb://localhost:27017/integration_tests', {native_parser: true}); How Express.js Works Connecting to Databases Statements to connect to databases don’t have to be in the beginning, as long as they are before step #7 “Starting the app” (from the list earlier in this section)—except in cases in which we use a database as a session store For example: var session = require('express-session'); var RedisStore = require('connect-redis')(session); app.use(session({ store: new RedisStore(options), secret: 'Pro Express.js rocks!' })); Most of the database drivers, such as Mongoskin7 and Mongoose8 , support buffering of the queries; this way, if the server is running before the connection has been established, the database queries will be buffered for later execution (when the database connection is established) How Express.js Works Configuring Express.js App Settings Simply put, configuring Express.js app settings consists of setting some values to string keys with app.set() Some of these keys are used by Express.js and augment its behavior, while others are arbitrary For example, if you are using the Jade template engine and *.jade files, use 'view engine' to let Express.js know that it needs to looks for *.jade files: app.set('view engine', 'jade'); You’ll find a lot more information about configuring settings in the following chapters Sometimes we want to store a custom value on the server object for future reference For example, we can assign port to a value from the environment variable PORT or, if it’s undefined, to 3000 so that we can use the value across all source code: app.set('port', process.env.PORT || 3000); How Express.js Works Defining Middleware Middleware is a special function that allows for better code organization and reuse Some of the middleware is packaged as third-party (NPM) modules and can be used right out of the box Other times, we can write our own custom middleware In both cases the syntax is app.use(): app.use(bodyParser.json()); How Express.js Works Defining Routes Routes can be either good old web pages or REST API endpoints In both cases the syntax is similar: we use app.VERB(), where VERB() is an HTTP method such as GET, POST, DELETE, PUT, OPTIONS, or PATCH For example, we can define home page (root) routes as app.get('/', renderHomePage); How Express.js Works Starting the App Finally, after everything is configured, we can boot up the server with server.listen(portNumber), where server is a core http server object created with the app object: var server = http.createServer(app); var boot = function () { server.listen(app.get('port'), function(){ console.info('Express server listening on port ' + app.get('port')); }); }; var shutdown = function() { server.close(); }; How Express.js Works If this file is included by another file (e.g., a test), we might want to export the server object instead of boot it up The way we perform a check is by using require.main === module; if it’s true, then this file wasn’t included by anything else The test will boot up the server by itself using the method boot() that we export We also export shutdown() and port: if (require.main === module) { boot(); } else { console.info('Running app as a module'); exports.boot = boot; exports.shutdown = shutdown; exports.port = app.get('port'); } How Express.js Works When an Express.js app is running, it listens to requests Each incoming request is processed according to a defined chain of middleware and routes, starting from the top and proceeding to the bottom This aspect is important because it allows you to control the execution flow For example, we can have multiple functions handling each request, and some of those functions will be in the middle (hence the name middleware): Parse cookie information and go to the next step when done Parse parameters from the URL and go to the next step when done Get the information from the database based on the value of the parameter if the user is authorized (cookie/session), and go to the next step if there is a match Display the data and end the response ... with Express. js quickly and without diving too deep into its API, we’ll cover these topics in this chapter: ● ● ● How Express. js works Express. js installation Express. js Generator installation How. .. comma: var express = require( 'express' ), compression = require('compression'), bodyParser = require('body-parser'), mongo = require('mongoskin'); How Express. js Works Instantiations To use Express. js,... instantiate any other objects: var app = express( ); var db = mongo.db('mongodb://localhost:27 017 /integration_tests', {native_parser: true}); How Express. js Works Connecting to Databases Statements

Ngày đăng: 17/11/2019, 07:37

TỪ KHÓA LIÊN QUAN