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

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.

主站蜘蛛池模板: 周宁县| 晋中市| 巨野县| 巴青县| 襄汾县| 渝北区| 伊宁县| 济南市| 贵州省| 武安市| 沂水县| 垫江县| 喜德县| 登封市| 蒙城县| 宁海县| 金昌市| 团风县| 定安县| 唐海县| 穆棱市| 大荔县| 耒阳市| 岚皋县| 枝江市| 湖北省| 台东县| 平顶山市| 教育| 清丰县| 红桥区| 高台县| 威海市| 浮山县| 东阿县| 哈巴河县| 香河县| 阿尔山市| 平江县| 冀州市| 大丰市|