请求对象 req
request
req.query一个对象,包含的是一键值对存放的查询字符串 用于get请求
app.get('/search',function (req,res) {
res.render('index',{
title: '博客项目',
cc:req.query.shoe.color
})
})
在浏览器中访问http://localhost:3000/search?q=111&shoe[color]=blue
页面上会输出blue
req.body一个对象,包含的是post请求参数,但是要是req.body这个可用,需要中间件来解析请求正 用于post请求
演示req.body对象的使用
index.ejs
<body>
<h1>测试post的提交</h1>
<form action="testPost" method="post">
<input type="text" name="user">
<input type="submit"value="提交">
</form>
<h1><%= cc %></h1>
</body>
在app.js中
app.post('/testPost',function (req,res) {
res.render('index',{
title: '博客项目',
cc:req.body.user
})
})
访问http://localhost:3000/ 可以测试
req.params 处理/:xx形式的get或者post请求 获取的是请求的参数
app.get('/hello/:username',function(req,res){
res.write("<h1>"+req.params.username+"</h1>");
res.end("<p>ddasdas</p>")
})
在浏览器其访问http://localhost:3000/hello/djdjisd会在页面上显示djdjisd和ddasdas
基于REST风格的路由控制
REST表征状态的转移,(Representionsal state Transfer)一种基于HTTP协议的网络应用的接口http协议定了一下几种标准的方法
GET POST
控制权转移
当访问任何被这两条同的规则匹配到达的路径,会发现请求总是被前一条路径捕获,后一条路径捕获不到,使用了Express提供的next控制权转移的方法之后,第二条路径就会捕获后面的规则
next来检查用户名是否存在,存在的话才给这个用户显示对应的页面,没有这个用户的话就报错
var users={
'ss':{
name:"sasa"
}
}
module.exports=function(app){
app.get('/',function(req,res){
res.render('index',{title:'商城'})
})
app.get('/hello/:username',function(req,res,next){
if(users[req.params.username]){
next()
}
else{
next(new Error('sa'));
}
})
app.get('/hello/:username',function(req,res){
res.send("<h1>"+req.params.username+"</h1>");
})
}