Express.js - req.accepts() 方法
req.accepts() 方法检查请求的 Accept HTTP 标头字段是否可以接受指定的内容类型。此方法返回最佳匹配,如果指定的任何内容类型都不可以接受,则返回 False。
类型值可以是 MIME 类型(例如 application/json),也可以是扩展名(例如 json)。
语法
req.accepts( types )
示例 1
以 "reqAccepts.js" 名称创建一个文件,并复制以下代码段。创建文件后,使用命令 "node reqAccepts.js" 运行此代码,如下面的示例所示 -
// req.accepts() Method Demo Example
// Importing the express module
var express = require('express');
// Initializing the express and port number
var app = express();
var PORT = 3000;
// Defining an endpoint with req.accepts() fn
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);
});输出
使用 GET 请求访问端点 localhost:3000/,并将内容类型设置为 'application/json',并将 Accept 设置为 'application/json'
C:\home
ode>> node reqAccepts.js Server listening on PORT 3000 application/json application/json
示例 2
让我们看另一个示例。
// req.accepts() Method Demo Example
// Importing the express module
var express = require('express');
// Initializing the express and port number
var app = express();
var PORT = 3000;
// Defining an endpoint with req.accepts() fn
app.get('/', function (req, res) {
console.log(req.get('Accept'));
console.log(req.accepts('text/html'));
res.end();
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});输出
使用 GET 请求访问端点 localhost:3000/,并将 内容类型设置为 'text/plain',并将 Accept 设置为 'text/plain'
C:\home
ode>> node reqAccepts.js Server listening on PORT 3000 text/plain false
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP