express 中文社区:http://expressjs.jser.us/community.htmlhtml
1. 首先是最基本的用法。node
1
2
3
4
5
|
var
app=require(
'express'
).createServer();
app.get(
"/"
,
function
(req,res){
res.send(
"hello world"
);
});
app.listen(3000);
|
当用户访问 127.0.0.1:3000的时候,页面会输出hello world正则表达式
2. 加个路径试试。express
1
2
3
4
5
6
7
|
var
app=require(
"express"
).createServer();
app.get(
"/toolmao"
,
function
(req,res){
res.send(
"welcome to toolmao"
);
});
app.listen(3000);
|
当用户访问 127.0.0.1:3000/toolmao的时候,就会输出welcome to toolmaoapp
3. 更为复杂一点的,能够把路径做为参数。curl
1
2
3
4
5
6
7
|
var
app=require(
"express"
).createServer();
app.get(
'/user/:id'
,
function
(req, res){
res.send(
'user '
+ req.params.id);
});
app.listen(3000);
|
当用户访问 127.0.0.1:3000/user/gainover 的时候,就会输出 user gainover函数
4. 3中的代码,也能够写为正则表达式的形式。post
1
2
3
4
5
6
7
|
var
app=require(
"express"
).createServer();
app.get(/\/user\/([^\/]+)\/?/,
function
(req, res){
res.send(req.params);
});
app.listen(3000);
|
这里能够根据你的须要进行正则的自定义。正则中的匹配结果,存储在req.params参数中。fetch
一个更复杂的正则的例子,以下:含有2个匹配。ui
1
2
3
|
app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/,
function
(req, res){
res.send(req.params);
});
|
请求时,输出以下:
1
2
3
4
5
6
7
8
|
$ curl http:
//dev:3000/user
[
null
,
null
]
$ curl http:
//dev:3000/users
[
null
,
null
]
$ curl http:
//dev:3000/users/1
[
"1"
,
null
]
$ curl http:
//dev:3000/users/1..15
[
"1"
,
"15"
]
|
5. 若是咱们想指定参数为id,同时又想用正则进行限制,能够写为:
/user/:id([0-9]+)
----------------------------------------------------------------------------
Route的依次执行
1. 当一个请求,可以匹配到多个route时,咱们能够调用内置的next函数,来依次进行处理。
例如:
1
2
3
4
5
6
7
8
9
10
11
12
|
app.get(
'/users/:id?'
,
function
(req, res, next){
var
id = req.params.id;
if
(id) {
// do something
}
else
{
next();
}
});
app.get(
'/users'
,
function
(req, res){
// do something else
});
|
当用户请求,/users/gainover时,能够进行某种处理,而当用户请求为/users/, id 不存在,则会调用next()函数,进而调用 app.get("/users/", ....);
2. 一个route里能够有多个处理函数。例如:
app.get('/users/:id/edit/',function1,function2,...);
一个实际的例子可能以下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
function
loadUser(req, res, next) {
// You would fetch your user from the db
var
user = users[req.params.id];
if
(user) {
req.user = user;
next();
}
else
{
next(
new
Error(
'Failed to load user '
+ req.params.id));
}
}
function
andRestrictToSelf(req, res, next) {
req.authenticatedUser.id == req.user.id
? next()
: next(
new
Error(
'Unauthorized'
));
}
app.get(
'/user/:id/edit'
, loadUser, andRestrictToSelf,
function
(req, res){
res.send(
'Editing user '
+ req.user.name);
});
|
当用户访问:/user/gainover/edit时,首先会调用第一个处理函数loadUser,判断用户是否存在于users中,若是不存在,经过next(new Error(msg)); 的方式抛出异常,不然,执行next(),而next此时实际就是指向 andRestrictToSelf 函数,而后判断当前登陆的id和被编辑的id是否等同,若是等同,则继续next(),从而执行 res.send( ...);