express之req res

request對象和response對象

Request

req.baseUrl 基礎路由地址
req.body post發送的數據解析出來的對象
req.cookies 客戶端發送的cookies數據
req.hostname 主機地址 去掉端口號
req.ip 查看客戶端的ip地址
req.ips 代理的IP地址
req.originalUrl 對req.url的一個備份
req.params 在使用/:id/:name 匹配params
req.path 包含請求URL的路徑部分
req.protocol http 或https協議
req.query 查詢字符串解析出來的對象 username=zhangsan&password=123 { username:zhangsan }
req.route 當前匹配的路由 正則表達式
req.params 獲取路由匹配的參數
req.get 獲取請求header裏的參數
req.is 判斷請求的是什麼類型的文件
req.param(key名稱) 用來獲取某一個路由匹配的參數javascript

Response

res.headersSent 查看http響應是否響應了http頭
res.append(名稱,value) 追加http響應頭
res.attachment(文件路徑) 響應文件請求
res.cookie() 設置cookiehtml

res.setHeader('Content-Type','text/html;charset=utf8')
res.append('Content-Type','text/html;charset=utf8')
res.append('hehe','1008')
res.append('haha','1008')
res.attachment('./xx.zip') //Content-Disposition: attachment; filename="xx.zip"
res.clearCookie(cookiename) 刪除cookie
res.cookie('zhangsan','lisi') 設置cookie
res.clearCookie('zhangsan') //清除cookie
res.download(文件的path路徑) 跟attachment相似 用來處理文件下載的 參數是文件地址
res.end() http模塊自帶的
res.format() 協商請求文件類型 format匹配協商的文件類型java

res.cookie('zhangsan1','lisi2',{
      maxAge:900000, //cookie的過時時間
      httpOnly:true,    //僅由服務端來設置cookie
      path: '/admin',    
      secure: true,
      signed:true
  })
  res.format({
      'text/plain': function(){
          res.send('hey');
      },
      
      'text/html': function(){
          res.send('<p>hey</p>');
      },
      
      'application/json': function(){
          res.send({ message: 'hey' });
      },
      
      'default': function() {
          // log the request and respond with 406
          res.status(406).send('Not Acceptable');
      }
  });

  res.get('key') 獲取響應header數據
  res.json() 返回json數據 會自動設置響應header Content-type 爲json格式 application/json

  res.json({
      xx:100
  })

  res.json({
      xx:100
  })

  jsonp 利用的就是瀏覽器加載其餘服務器的文件不會存在跨域問題
  ajax請求就會有跨域問題

  res.setHeader('Content-Type','text/javascript;charsert=utf8')
  res.end(`typeof ${req.query.callback} == 'function' ? ${req.query.callback}({aa:100}):null`)

  res.jsonp({aaa:100})


  重定向 把訪問的地址跳轉到另外一個地址上
  res.redirect(301,'/api/aes')

  express jade
  res.render('index',{title:"hehe",test:"23"})
  res.send('') 發送數據 能夠是任意類型的數據
  res.sendFile() 發送文件的 
  res.sendStatus(200) 設置發送時的狀態碼
  res.set('Content-Type', 'text/plain') //設置響應header
  res.status(200) // 設置狀態碼
  res.type('') // 直接設置響應的文件類型

  res.type('pdf')

  res.send({aa:100})
  res.end('ok')
  res.end({aa:100})

  res.end('你好')


  res.end(req.get('Accept-Language'))
  res.json({
      is:req.is('text/html')
  })

  res.json({
      type:req.baseUrl,
      hostname:req.hostname,
      // ip:req.ip,
      // ips:req.ips,
      // route:req.route,
      ct:req.get('Accept'),
      cs:'22'
  })


router.get('/:id/:date',(req,res)=>{
  console.log(req.params)
  // res.json(req.params)
  res.end(req.param('date'))
})

router.get('/aes',(req,res)=>{
  res.json({
      type:req.baseUrl
  })
})
相關文章
相關標籤/搜索