node+express----请求对象req

请求对象 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>");
    })
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值