官术网_书友最值得收藏!

Getting acquainted with Express

Express (http://expressjs.com/) is a web application framework for Node.js. It is built on top of Connect (http://www.senchalabs.org/connect/), which means that it implements middleware architecture. In the previous chapter, when exploring Node.js, we discovered the benefit of such a design decision: the framework acts as a plugin system. Thus, we can say that Express is suitable for not only simple but also complex applications because of its architecture. We may use only some of the popular types of middleware or add a lot of features and still keep the application modular.

In general, most projects in Node.js perform two functions: run a server that listens on a specific port, and process incoming requests. Express is a wrapper for these two functionalities. The following is basic code that runs the server:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

This is an example extracted from the official documentation of Node.js. As shown, we use the native module http and run a server on the port 1337. There is also a request handler function, which simply sends the Hello world string to the browser. Now, let's implement the same thing but with the Express framework, using the following code:

var express = require('express');
var app = express();
app.get("/", function(req, res, next) {
  res.send("Hello world");
}).listen(1337);
console.log('Server running at http://127.0.0.1:1337/');

It's pretty much the same thing. However, we don't need to specify the response headers or add a new line at the end of the string because the framework does it for us. In addition, we have a bunch of middleware available, which will help us process the requests easily. Express is like a toolbox. We have a lot of tools to do the boring stuff, allowing us to focus on the application's logic and content. That's what Express is built for: saving time for the developer by providing ready-to-use functionalities.

主站蜘蛛池模板: 措勤县| 三亚市| 崇义县| 大洼县| 无棣县| 遂平县| 社旗县| 惠来县| 南丹县| 武川县| 汕头市| 新龙县| 乐昌市| 阜新| 彰化县| 阿图什市| 泾川县| 荣昌县| 大石桥市| 双桥区| 承德县| 马尔康县| 德令哈市| 吉林省| 讷河市| 灵璧县| 金昌市| 虞城县| 闻喜县| 昭通市| 周至县| 宜州市| 池州市| 贵港市| 祁连县| 东海县| 寿光市| 顺平县| 库车县| 顺昌县| 夹江县|