express . js req . accept()功能

原文:https://www . geesforgeks . org/express-js-req-accepts-function/

req . Accept()函数根据请求的 Accept HTTP 头字段检查指定的内容类型是否可接受。方法返回最佳匹配,否则如果指定的内容类型都不可接受,则返回 false。

语法:

req.accepts( types )

参数:类型值是单个 MIME 类型字符串。

返回值:字符串

快递模块安装:

  1. 您可以访问安装快速模块的链接。您可以使用此命令安装此软件包。

    js npm install express

  2. 安装快速模块后,您可以使用命令在命令提示符下检查您的快速版本。

    js npm version express

  3. 之后,您可以创建一个文件夹并添加一个文件,例如 index.js。

    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'));    
    console.log(req.accepts('application/json')); 
    res.end();
});

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

运行程序的步骤:

  1. 项目结构会是这样的:
  2. 使用以下命令确保您已经安装了 express 模块:

    js npm install express

  3. Run index.js file using below command:

    js node index.js

    输出:

    ```js Server listening on PORT 3000

    ```

  4. 现在向 http://localhost:3000/ 发出 GET 请求,头部设置为‘Accept:application/JSON’,然后您将在控制台上看到以下输出:

    ```js Server listening on PORT 3000 application/json application/json

    ```

示例 2: 文件名:index.js

var express = require('express');
var app = express();
var PORT = 3000;

app.get('/', function (req, res) {
    console.log(req.get('Accept'));    
    console.log(req.accepts('text/plain')); 
    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 请求,头部设置为“接受:应用/JSON”,然后您将在控制台上看到以下输出:

Server listening on PORT 3000
application/json
false

参考:T2】https://expressjs.com/en/5x/api.html#req.accepts