>  기사  >  웹 프론트엔드  >  Express Routing 및 미들웨어의 Node.js 개발 세부 코드 예제

Express Routing 및 미들웨어의 Node.js 개발 세부 코드 예제

黄舟
黄舟원래의
2017-03-25 14:35:181214검색

이 글은 주로 nodejs 개발 - 익스프레스 라우팅과 미들웨어를 소개합니다. 편집자는 이것이 꽤 좋다고 생각합니다. 이제 여러분과 공유하고 참고용으로 제공하겠습니다. 편집기를 따라가서 살펴보겠습니다.

Routing

일반적으로 HTTP URL의 형식은 다음과 같습니다.

host[:port][path]

http는 프로토콜을 나타냅니다.

host는 호스트를 의미합니다.

port는 포트이며 선택 필드입니다. 제공되지 않은 경우 기본값은 80입니다.

path는 요청된 리소스의 URI(Uniform Resource Identifier, Universal Resource Locator)를 지정합니다. URL에 경로가 제공되지 않은 경우 일반적으로 기본값은 "/"입니다(보통 브라우저 또는 기타 도구로 보완됨). HTTP 클라이언트) 우수).

소위 라우팅은 HTTP 요청에서 경로 부분을 처리하는 방법입니다. 예를 들어, URL "xxx.com/users/profile"의 경우 라우팅에 따라 /users/profile 경로를 처리하는 방법이 결정됩니다.

Node.js 개발 시작하기 - 빠른 설치 및 사용에서 제공한 HelloWorld 코드의 빠른 버전을 검토해 보겠습니다.

var express = require('express');
var app = express();

app.get('/', function (req, res) {
 res.send('Hello World!');
});

app.listen(8000, function () {
 console.log('Hello World is listening at port 8000');
});

위 코드의 app.get() 호출은 실제로 우리 웹 사이트에 경로가 추가되고 get의 두 번째 매개 변수로 표시되는 함수 에 의해 "/" 경로가 처리되도록 지정됩니다.

express 객체는 다음 방법을 사용하여 일반적인 HTTP 방법에 대한 경로를 지정할 수 있습니다.

app.METHOD(path, callback [, callback ...])

경로 경로

문자열 을 사용한 라우팅 경로의 예:

// 匹配根路径的请求

app.get('/', function (req, res) {

 res.send('root');

});

// 匹配 /about 路径的请求

app.get('/about', function (req, res) {

 res.send('about');

});

// 匹配 /random.text 路径的请求

app.get('/random.text', function (req, res) {

 res.send('random.text');

});

使用字符串模式的路由路径示例:

// 匹配 acd 和 abcd

app.get('/ab?cd', function(req, res) {

 res.send('ab?cd');

});

// 匹配 abcd、abbcd、abbbcd等

app.get('/ab+cd', function(req, res) {

 res.send('ab+cd');

});

// 匹配 abcd、abxcd、abRABDOMcd、ab123cd等

app.get('/ab*cd', function(req, res) {

 res.send('ab*cd');

});

// 匹配 /abe 和 /abcde

app.get('/ab(cd)?e', function(req, res) {

 res.send('ab(cd)?e');

});

문자 ?, +, * 및 ()는 정규식 의 하위 집합입니다. , - 및 .는 문자열 기반 경로에서 문자 그대로 해석됩니다.

정규식을 사용한 라우팅 경로의 예:

// 匹配任何路径中含有 a 的路径:

app.get(/a/, function(req, res) {

 res.send('/a/');

});

// 匹配 butterfly、dragonfly,不匹配 butterflyman、dragonfly man等

app.get(/.*fly$/, function(req, res) {

 res.send('/.*fly$/');

});

경로 핸들

은 요청 처리를 위해 여러 콜백을 제공할 수 있습니다. 🎜>는 미들웨어처럼 동작합니다. 유일한 차이점은 이러한 콜백 함수가 next('route') 메서드를 호출하고 다른 경로 콜백 함수를 건너뛸 수 있다는 것입니다. 이 메커니즘은 라우팅을 위한 전제 조건을 정의하는 데 사용될 수 있으며, 기존 경로에서 계속 실행하는 것이 타당하지 않은 경우 나머지 경로에 제어권을 줄 수 있습니다.

경로 핸들은 다양한 형태로 제공되며 아래와 같이 함수, 함수 배열 또는 이 둘의 혼합일 수 있습니다.

콜백 함수를 사용하여 라우팅을 처리합니다. 🎜>
app.get('/example/a', function (req, res) {

 res.send('Hello from A!');

});

여러 콜백 함수를 사용하여 라우팅 처리(다음 객체 지정을 기억하세요):

app.get('/example/b', function (req, res, next) {

 console.log('response will be sent by the next function ...');

 next();

}, function (req, res) {

 res.send('Hello from B!');

});

콜백 함수 배열을 사용하여 라우팅 처리:

var cb0 = function (req, res, next) {

 console.log('CB0');

 next();

}

var cb1 = function (req, res, next) {

 console.log('CB1');

 next();

}

var cb2 = function (req, res) {

 res.send('Hello from C!');

}

app.get('/example/c', [cb0, cb1, cb2]);

혼합

함수 사용

및 함수 배열 처리 라우팅:

var cb0 = function (req, res, next) {

 console.log('CB0');

 next();

}

var cb1 = function (req, res, next) {

 console.log('CB1');

 next();

}

app.get('/example/d', [cb0, cb1], function (req, res, next) {

 console.log('response will be sent by the next function ...');

 next();

}, function (req, res) {

 res.send('Hello from D!');
METHOD는 app.get, app.post 등 GET 및 POST와 같은 HTTP 메서드의 소문자일 수 있습니다. 경로 부분은 문자열 리터럴이거나 정규 표현식일 수 있습니다. 가장 간단한 예는 이전 코드의 app.get() 호출에서 '/' 매개변수를 '*'로 변경하는 것인데, 의미가 달라집니다. 변경 전에는 "localhost:8000" 또는 "localhost:8000/" 형식의 액세스만 "Hello World!"를 반환했지만, 변경 후에는 "localhost:8000/xxx/yyyy.zz"가 반환합니다. 또한 "Hello World!"를 반환합니다.

express를 사용하여 웹 서버를 구축할 때 특정 경로, 즉 라우팅 처리에 대한 요청에 어떻게 응답할지 결정하는 작업에서 매우 중요한 부분입니다.

가장 직접적인 경로 구성 방법은 app.get() 및 app.post()를 호출하여 하나씩 구성하는 것입니다. 그러나 많은 경로를 처리해야 하는 웹사이트의 경우 이는 생명을 위협합니다. . 따라서 실제 개발에서는

라우팅 매개변수

(쿼리 문자열, 정규식, 사용자 정의 매개변수, 사후 매개변수)를 결합하여 작업 부하를 줄이고 유지 관리성을 향상시켜야 합니다.

미들웨어

Express에는 미들웨어라는 개념이 있습니다. 소위 미들웨어는 요청을 받은 후 응답을 보내기 전에 이 단계에서 실행되는 일부 기능을 말합니다.

경로의 처리 체인에 미들웨어를 삽입하려면 Express 개체의 use 메서드를 사용할 수 있습니다. 이 메소드의 프로토타입은 다음과 같습니다.

app.use([path,] function [, function...])

app.use가 경로 매개변수를 제공하지 않는 경우 경로는 기본적으로 "/"로 설정됩니다. 특정 경로에 대한 미들웨어를 설치하면 해당 경로를 기반으로 하는 경로에 액세스할 때마다 미들웨어가 적용됩니다. 예를 들어 "/abcd"에 대한 미들웨어를 설정하면 "/abcd/xxx"에 액세스할 때에도 미들웨어가 적용됩니다.

미들웨어 기능의 프로토타입은 다음과 같습니다.

function (req, res, next)

첫 번째 매개변수는 요청 객체 req입니다. 두 번째 매개변수는 응답 객체 res입니다. 세 번째는 미들웨어 호출 체인을 구동하는 데 사용되는 함수입니다. 후속 미들웨어가 요청을 계속 처리하도록 하려면 next 메서드를 호출해야 합니다.

미들웨어 기능을 특정 경로에 적용하기 위한 일반적인 호출은 다음과 같습니다.

app.use('/abcd', function (req, res, next) {
 console.log(req.baseUrl);
 next();
})

app.static middleware

Express는 정적 미들웨어를 제공합니다. 웹사이트의

정적

파일에 대한 GET 요청을 처리하는 데 사용할 수 있으며 express.static을 통해 액세스할 수 있습니다. express.static의 사용법은 다음과 같습니다.

express.static(root, [options])

第一个参数root,是要处理的静态资源的根目录,可以是绝对路径,也可以是相对路径。第二个可选参数用来指定一些选项,比如maxAge、lastModified等,

一个典型的express.static应用如下:

var options = {
 dotfiles: 'ignore',
 etag: false,
 extensions: ['htm', 'html'],
 index: false,
 maxAge: '1d',
 redirect: false,
 setHeaders: function (res, path, stat) {
  res.set('x-timestamp', Date.now());
 }
}

app.use(express.static('public', options));

上面这段代码将当前路径下的public目录作为静态文件,并且为Cache-Control头部的max-age选项为1天。还有其它一些属性,请对照express.static的文档来理解。

使用express创建的HelloExpress项目的app.js文件里有这样一行代码:

app.use(express.static(path.join(dirname, 'public')));

这行代码将HelloExpress目录下的public目录作为静态文件交给static中间件来处理,对应的HTTP URI为“/”。path是一个Node.js模块,dirname是Node.js的全局变量,指向当前运行的js脚本所在的目录。path.join()则用来拼接目录。

有了上面的代码,你就可以在浏览器里访问“localhost:3000/stylesheets/style.css”。我们做一点改动,把上面的代码修改成下面这样:

app.use('/static', express.static(path.join(dirname, 'public')));

上面的代码呢,针对/static路径使用static中间件处理public目录。这时你再用浏览器访问“localhost:3000/stylesheets/”就会看到一个404页面,将地址换成“localhost:3000/static/stylesheets/style.css”就可以了。

Router

Express还提供了一个叫做Router的对象,行为很像中间件,你可以把Router直接传递给app.use,像使用中间件那样使用Router。另外你还可以使用router来处理针对GET、POST等的路由,也可以用它来添加中间件,总之你可以将Router看作一个微缩版的app。

下面的代码创建一个Router实例:

var router = express.Router([options]);

然后你就可以像使用app一样使用router:

// invoked for any requests passed to this router
router.use(function(req, res, next) {
 // .. some logic here .. like any other middleware
 next();
});

// will handle any request that ends in /events
// depends on where the router is "use()'d"
router.get('/events', function(req, res, next) {
 // ..
});

定义了router后,也可以将其作为中间件传递给app.use:

app.use('/events', router);

上面这种用法,会针对URL中的“/events”路径应用router,你在router对象上配置的各种路由策略和中间件,都会被在合适的时候应用。

路由模块

express工具创建的应用,有一个routes目录,下面保存了应用到网站的Router模块,index.js和user.js。这两个模块基本一样,我们研究一下index.js。

下面是index.js的内容:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
 res.render('index', { title: 'Express' });
});

module.exports = router;

index.js创建了一个Router实例,然后调用router.get为“/”路径应用了路由函数。最后呢使用module.exports将Router对象导出。

下面是app.js里引用到index.js的代码:

var routes = require('./routes/index');
...
app.use('/', routes);

第一处,require(‘./routes/index')将其作为模块使用,这行代码导入了index.js,并且将index.js导出的router对象保存在变量routes里以供后续使用。注意,上面代码里的routes就是index.js里的router。

第二处代码,把routes作为一个中间件,挂载到了“/”路径上。

模块

前面分析index.js时看到了module.exports的用法。module.exports用来导出一个Node.js模块内的对象,调用者使用require加载模块时,就会获得导出的对象的实例。

我们的index.js导出了Router对象。app.js使用require(‘./routes/index')获取了一个Router实例。

module.exports还有一个辅助用法,即直接使用exports来导出。

exports.signup = function(req, res){
 //some code
}

exports.login = function(req, res){
 //some code
}

上面的代码(假定在users.js文件里)直接使用exports来导出。当使用exports来导出时,你设置给exports的属性和方法,实际上都是module.exports的。这个模块最终导出的是module.exports对象,你使用类似“exports.signup”这种形式设置的方法或属性,调用方在require后都可以直接使用。

使用users模块的代码可能是这样的:

var express = require('express');
var app = express();
...
var users = require('./routes/users');
app.post('/signup', users.signup);
app.post('/login', users.login);
...

1.  什么是router路径,什么是middleware?

我们输入www.baidu.com 来访问百度的主页,浏览器会自动转换为 www.baidu.com:80/(省略一些参数)。 http://代表我们同服务器连接使用的是http协议,www.baidu.com 代表的是服务器的主机地址,会被我们的pc通过DNS解析为IP地址。80是默认的应用层端口。/ 即为我们访问的服务器(www.baidu.com)的路径,服务器要对我们访问的这个路径做出响应,采取一定的动作。我们可以把这一过程看做一个路由。

 访问的路径‘/'即为router的路径,服务器采取的动作即为middleware,即为一个个特殊的函数。

2. router路径

www.baidu.com/test: 路径为 /test

www.baidu.com/test?name=1&number=2: 路径同样为/test, ?后面会被服务器理解传给路径的参数。

3. Middleware

An Express application is essentially a stack of middleware which are executed serially.(express应用其实就是由一系列顺序执行的Middleware组成。)

A middleware is a function with access to the request object (req), the response object (res), and the next middleware in line in the request-response cycle of an Express application. It is commonly denoted by a variable named next. Each middleware has the capacity to execute any code, make changes to the request and the reponse object, end the request-response cycle, and call the next middleware in the stack. Since middleware are execute serially, their order of inclusion is important.(中间件其实就是一个访问express应用串入的req,res,nex参数的函数,这个函数可以访问任何通过req,res传入的资源。)

If the current middleware is not ending the request-response cycle, it is important to call next() to pass on the control to the next middleware, else the request will be left hanging.(如果当前中间件没有完成对网页的res响应 ,还可以通过next把router 留给下一个middleware继续执行)

With an optional mount path, middleware can be loaded at the application level or at the router level. Also, a series of middleware functions can be loaded together, creating a sub-stack of middleware system at a mount point.

路由的产生是通过HTTP的各种方法(GET, POST)产生的,Middleware可以跟router路径跟特定的HTTP方法绑定,也可以跟所有的方法绑定。

3.1 通过express应用的use(all),把Middleware同router路径上的所有HTTP方法绑定:

 app.use(function (req, res, next) {
  console.log('Time: %d', Date.now());
  next();
 })

3.2 通过express应用的http.verb,把Middleware同router路径上的特定的HTTP方法绑定:

app.get('/', function(req, res){
 res.send('hello world');
});


app.post('/', function(req, res){
 res.send('hello world');
});

4.  Express的Router对象

当express实例的路由越来越多的时候,最好把路由分类独立出去,express的实例(app) 能更好的处理其他逻辑流程。Express的Router对象是一个简化的 app实例,只具有路由相关的功能,包括use, http verbs等等。最后这个Router再通过app的use挂载到app的相关路径下。

 var express = require('express');
var app = express();
var router = express.Router();

// simple logger for this router's requests
// all requests to this router will first hit this middleware
router.use(function(req, res, next) {
 console.log('%s %s %s', req.method, req.url, req.path);
 next();
});

// this will only be invoked if the path ends in /bar
router.use('/bar', function(req, res, next) {
 // ... maybe some additional /bar logging ...
 next();
});

// always invoked
router.use(function(req, res, next) {
 res.send('Hello World');
});

app.use('/foo', router);

app.listen(3000);

router的路由必须通过app.use和app.verbs 挂载到app上才能被响应。所以上述代码,只有在app捕捉到 /foo路径上的路由时,才能router中定义的路由,虽然router中有针对 '/' 的路由,但是被app中的路由给覆盖了。

附:app.verbs和app.use的路由路径区别:

先看一段测试代码:

var express = require('express');

var app = express();
var router = express.Router();

app.get('/', function(req, res){
   console.log('test1');
});

app.use('/', function(req, res){
   console.log('test2');
});

router.get('/', function(req, res){
   console.log('test3');
});

app.listen(4000);

输入url: localhost:4000

输出结果:test1 

输入url: localhost:4000/hello

输出结果:test2

结论:app.get挂载‘/'的路由只响应跟'/'精确匹配的GET请求。 而app.use挂载的'/'的路由响应所有以'/' 为起始路由的路由,且不限制HTTP访问的方法。以下说明:Mounting a middleware at a path will cause the middleware function to be executed whenever the base of the requested path matches the path.

위 내용은 Express Routing 및 미들웨어의 Node.js 개발 세부 코드 예제의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.