如果想处理这个网址的任何method的请求,那么就写all
app.all("/",function(){
})
网址不区分大小写,即用
app.get("/AAb",function (req,res) {
res.send("你好");
})
用网址”/aab”也可以访问
所有的参数?后面的参数,锚点也会被忽略
也就是说,你路由到”/a”,实际上/a?id=2&sex=nan也可以被处理
正则表达式可以使用。
正则表达式中,未知部分用圆括号分组,然后可以用req.params[0],[1]得到,req.params类数组对象
app.get(/^\/student\/([\d]{10})$/,function (req,res) {
res.writeHead(200,{'Content-Type':'text/html;charset=UTF8'});
res.end("学生信息,学号"+req.params[0]);
})
使用冒号
app.get("/student/:id",function (req,res) {
var id = req.params["id"];
res.send(id);
})
app.get("/student/:id",function (req,res) {
var id = req.params["id"];
var test = /^[\d]{6}$/;
if(test.test(id)){
res.send(id);
}else{
res.send("请检查格式");
}
})
app.get("/:username/:oid",function (req,res) {
var username = req.params["username"];
var oid = req.params["oid"];
res.send(username+oid);
})
中间件
如果在get,post回调函数中没有next参数,那匹配上第一个路由之后,就不会往下继续匹配了。如果向往下继续匹配的话,那就需要写next()
app.get("/",function (req,res,next) {
console.log(1);
next();
})
app.get("/",function (req,res) {
console.log(2);
})
来看下面这段代码:
app.get("/:student/:id",function (req,res) {
console.log(1);
res.send("用户信息"+req.params.username);
})
app.get("/admin/:login",function (req,res) {
console.log(2);
res.send("管理员登录")
})
这时我们会发现一个问题,admin可以被当做用户名,login可以被当做id
那我们该怎么办?
解决方法:
解决方法一:
交换位置,也就是说express()中所有的路由(中间件)的顺序至关重要,匹配上第一个,就不会往下继续匹配
app.get("/admin/:login",function (req,res) {
console.log(2);
res.send("管理员登录")
})
app.get("/:student/:id",function (req,res) {
console.log(1);
res.send("用户信息"+req.params.username);
})
解决方法2
app.get("/:username/:id",function (req,res,next) {
var username = req.params.username;
//检索数据库,如果username存在,那么next()
if(检索数据库){
console.log(1);
res.send("用户信息"+req.params.username);
}else{
next();
}
})
app.get("/admin/:login",function (req,res) {
console.log(2);
res.send("管理员登录")
})
app.use()是一个中间件,与get和post不同的是,它的网址不是精确匹配的。而是能够有小文件拓展的。比如网址: hhtp://127.0.0.1:3000/admin/aa/bb/cc/dd
app.use("/admin",function (req,res) {
res.writeHead(200,{'Content-Type':'text/html;charset=UTF8'});
res.write(req.originalUrl+"<br>"); // admin/aa/bb/cc/dd
res.write(req.baseUrl+"<br>"); // admin
res.write(req.path+"<br>");// aa/bb/cc/dd
res.end("你好");
})
//当不写路径的时候,实际就相当于"/"所有的网址
app.use("/",function (req,res,next) {
console.log(new Date());
next();
})
app.use("/admin",function (req,res) {
res.writeHead(200,{'Content-Type':'text/html;charset=UTF8'});
res.write(req.originalUrl+"<br>");
res.write(req.baseUrl+"<br>");
res.write(req.path+"<br>");
res.end("你好");
})
每访问一个网址的时候,都会执行app.use(“/”,function(){
})里面的操作
如果访问网址是“/admin”以及其拓展名”/admin/…”上面的两个函数都执行
内容渲染
1.大多数情况下,渲染内容用res.render(),将根据views中的模板文件进行渲染,如果不想使用views文件夹,可以自己设置一个文件夹的名字,app.set(“view”,”haha”);
2.如果想要写一个快速测试页,当然也可以使用res.send()。这个函数将根据内容,自动帮我们设置Content-Type头部和200状态码。send只能用一次,和end一样。不同之处在于,send可以自动设置MIME类型
3.如果想使用不同的状态码,可以用:
res.status(404).send('Sorry,We cannot find that!');
4.如果想使用不同的Content-Type,可以使用:
res.set('Content-Type','text/html');