📜  Express.js req.acceptsCharsets()函数

📅  最后修改于: 2022-05-13 01:56:50.890000             🧑  作者: Mango

Express.js req.acceptsCharsets()函数

req.acceptsCharsets()函数根据请求的 Accept-Charset HTTP 标头字段返回指定字符集的第一个接受的字符集,否则如果不接受任何指定的字符集,则返回 false。

句法:

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

参数: charset 参数是 'UTF-8' 等字符集代码。

返回值:字符串(如果为真)或假。

express模块的安装:

  1. 您可以访问安装 express 模块的链接。您可以使用此命令安装此软件包。
    npm install express
  2. 安装 express 模块后,您可以使用命令在命令提示符下检查您的 express 版本。
    npm version express
  3. 之后,您可以创建一个文件夹并添加一个文件,例如 index.js。要运行此文件,您需要运行以下命令。
    node index.js

示例 1:文件名:index.js

var express = require('express');
var app = express();
var PORT = 3000;
  
app.get('/', function (req, res) {
    console.log(req.get('Accept-Charset'));    
    console.log(req.acceptsCharsets('UTF-8')); 
    res.end();
});
  
app.listen(PORT, function(err){
    if (err) console.log(err);
    console.log("Server listening on PORT", PORT);
});

运行程序的步骤:

  1. 项目结构将如下所示:
  2. 确保您已使用以下命令安装express模块:
    npm install express
  3. 使用以下命令运行 index.js 文件:
    node index.js

    输出:

    Server listening on PORT 3000
    
  4. 现在向http://localhost:3000/发出 GET 请求,标头设置为' Accept-Charset: UTF-8' ,然后您将在控制台上看到以下输出:
    Server listening on PORT 3000
    UTF-8
    UTF-8
    

示例 2:文件名:index.js

var express = require('express');
var app = express();
var PORT = 3000;
  
app.get('/', function (req, res) {
    console.log(req.get('Accept-Charset'));    
    console.log(req.acceptsCharsets('ISO-8859-1'));
    res.end();
});
  
app.listen(PORT, function(err){
    if (err) console.log(err);
    console.log("Server listening on PORT", PORT);
});

使用以下命令运行 index.js 文件:

node index.js

现在向http://localhost:3000/发出 GET 请求,标头设置为' Accept-Charset: UTF-8' ,然后您将在控制台上看到以下输出:

Server listening on PORT 3000
UTF-8
false

参考: https://expressjs.com/en/5x/api.html#req.acceptsCharsets