Express.js – req.acceptsCharsets() 方法


req.acceptsCharsets() 方法返回指定字元集集合中第一個被接受的字元集。這些字元集基於請求的 Accept-Charset HTTP 頭欄位。預設情況下,如果未接受指定字元集中的任何字元集,則它返回 'false'。

語法

req.acceptsCharsets ( charset, [...] )

示例 1

建立一個名為 "reqAcceptsCharsets.js" 的檔案,並複製以下程式碼段。建立檔案後,使用命令 "node reqAcceptsCharsets.js" 執行此程式碼,如下例所示 −

// res.acceptsCharsets(lang, [...]) Method Demo Example
// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint
app.get('/api', function (req, res) {
   console.log(req.acceptsCharsets('UTF-8'));
   console.log("Charset Received: ", req.get('Accept-Charset'));
   res.end();
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

輸出

使用 GET 請求訪問以下端點 "localhost:3000/api",並在頭中設定以下屬性:Accept-Charsets = UTF-8

C:\home
ode>> node reqAcceptsCharsets.js Server listening on PORT 3000 Charset Received: UTF-8 UTF-8

示例 2

讓我們再看一個示例。

// res.acceptsCharsets(lang, [...]) Method Demo Example
// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint
app.get('/api', function (req, res) {
   console.log("Is valid charset: ", req.acceptsCharsets('ISO-8859-1'));
   console.log("Charset Received: ", req.get('Accept-Charset'));
   res.end();
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

輸出

使用 GET 請求訪問端點 "localhost:3000/api",並在頭中設定以下屬性 - Accept-Language = UTF-8

C:\home
ode>> node reqAcceptsCharsets.js Server listening on PORT 3000 Is valid charset: false Charset Received: UTF-8

更新日期:06-4-2022

160 次瀏覽

開啟您的職業生涯

完成課程獲取相關認證

開始
廣告
© . All rights reserved.