Express-Request請求和Response響應篇 請求對象Request 返回對象Response

請求對象Request

當請求路由的時候會計入路由的處理方法中,這個方法本質是中間件,包括三個參數,即請求對象Request,返回對象Response和執行下一步方法 next

Request 常用屬性

Request.url屬性 獲取請求地址

router.get('/iwhao', function(req, res, next) {
  console.log(req.url) // 當訪問路由/iwhao時控制檯會打印 /iwhao
  res.render('index', { title: 'Express' });
});

Request.query 獲取url?後參數

router.get('/iwhao?page=11231313', function(req, res, next) {
 // 當訪問路由 /iwhao?page=11231313 時控制檯會打印 11231313
  console.log(req.query.page)
  res.render('index', { title: 'Express' });
});

Request.params 獲取url中的自定義參數

router.get('/iwhao/:id', function(req, res, next) {
  console.log(req.params) 
  res.render('index', { title: 'Express' });
});

當訪問路由/iwhao/123123 時控制檯會打印 {id: '123123'}

Request.body 獲取post請求參數

和get獲取參數方式一樣,Express 已經將POST 請求參數封裝在了Request.body對象中,同樣是以鍵值對的形式存在,方便獲取處理 代碼如下

router.post('/iwhao', function(req, res, next) {
  console.log(req.body) 
  res.render('index', { title: 'Express' });
});

Request.headers 屬性獲取請求頭數據

router.post('/iwhao', function(req, res, next) {
  console.log(req.headers) 
  res.send(req.headers);
});

藉助postman 接口請求工具 在headers中傳入鍵爲name值爲chaoren的參數,然後請求後返回結果如下可以獲取到請求頭中的默認和自定義數據

返回對象Response

上面說了請求,既然有個請求,那肯定有相應返回值,下面介紹返回對象Response

Response.render 方法

Response.send() 方法 發送http響應

send() 方法 只發送一個https響應至請求端,只接收一個參數,這個參數可以是任何類型

之所以可以接收任何類型的參數是因爲執行這個方法的時候會自動設置響應頭數據類型,即響應頭裏Conten-Type字段 1.當參數爲Buffer對象時 Response.send() 將Conten-Type響應頭字段設置爲application/octet-stream

router.get(/iwhao/, function(req, res, next) {
  res.send(Buffer('<p>我是213131313</p>'));
});

在Postman 中查看請求,會發現返回的響應頭中Conten-Type字段值爲 application/octet-stream

2.當參數爲String時 Response.send()方法將將Conten-Type響應頭字段設置爲text/html

res.send('<p>I am iron man</p>');

3.當參數爲Array或Object時 Response.send()方法將將Conten-Type響應頭字段設置爲application/json;

res.send([1,2,3,4,5]);
res.send({name:'iron man'});

Response.json() 返回JSON格式的數據

除了之前使用模板返回html頁面之外,返回json格式的數據也是目前最爲流行的,也可以叫做 api接口, 尤其是在前後端分離的開發模式下,更爲用途廣泛,所有學習怎樣返回json 數據也很重要

res.json({
    name:'iron man',
    title:'無敵'
})

Response.json() 方法只接受一個參數,可以是任何的Json格式類型,包括對象、數組字符串

Response.status() 設定http狀態碼

// res.status(500).end()
res.status(403).end()

使用res.status 後一定要寫 end() 或者send和json方法當結尾,因爲status 只是設置狀態,並沒有返回結果

Response.redirect() 重定向 跳轉 指定路由

訪問/iwhao 會跳轉到 /ceshi

router.get(/iwhao/, function(req, res, next) {
  res.redirect('/ceshi')
});
router.get('/ceshi', function(req, res, next) {
  res.json({name:'iron man'});
});

Response.redirect() 還可以設定 http狀態碼

res.redirect(301,'/ceshi')

作者:iwhao_top
鏈接:https://juejin.cn/post/6992351373392248839
來源:掘金

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章