當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Express.js res.format()用法及代碼示例

res.format()函數對請求對象上的Accept HTTP標頭執行content-negotiation(如果存在)。此函數檢查Accept HTTP請求標頭,然後根據Accept值調用相應的處理程序。

用法:

res.format(object)

快遞模塊的安裝:

  1. 您可以訪問安裝Express模塊​​的鏈接。您可以使用此命令安裝此軟件包。
    npm install express
  2. 安裝Express模塊​​後,可以使用命令在命令提示符下檢查Express版本。
    npm version express
  3. 之後,您可以僅創建一個文件夾並添加一個文件,例如index.js。要運行此文件,您需要運行以下命令。
    node index.js

文件名:index.js

var express = require('express'); 
var app = express(); 
var PORT = 3000; 
  
app.get('/', function(req, res){ 
    res.format({ 
        html:function () { 
          res.send('<p>Greetings from GeeksforGeeks</p>'); 
        }, 
        text:function () { 
          res.send('Greetings from GeeksforGeeks'); 
        },       
        json:function () { 
          res.send({ message:'Greetings from GeeksforGeeks' }); 
        } 
    }); 
}); 
  
app.listen(PORT, function(err){ 
    if (err) console.log(err); 
    console.log("Server listening on PORT", PORT); 
});

在上麵的示例中,當Accept標頭字段設置為“ application /json”時,輸出為{“message”:“Greetings from GeeksforGeeks”},如果Accept標頭字段設置為“ text /plain”,我們將得到“Greetings from GeeksforGeeks”消息作為響應。

運行程序的步驟:

  1. 項目結構將如下所示:
  2. 確保使用以下命令安裝了Express模塊​​:
    npm install express
  3. 使用以下命令運行index.js文件:
    node index.js

    輸出:

    Server listening on PORT 3000
    
  4. 打開瀏覽器並轉到http://localhost:3000 /,現在您可以在屏幕上看到以下輸出。
    Greetings from GeeksforGeeks

相關用法


注:本文由純淨天空篩選整理自gouravhammad大神的英文原創作品 Express.js | res.format() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。