类型
推断请求的内容类型。
安装
$ npm install type-is
API
import { createServer } from "http";
import { TypeIs } from "type-is";
const isText = new TypeIs(["text/*"]);
createServer(function (req, res) {
res.end(
"you " + (isText.request(req) ? "sent" : "did not send") + " me text",
);
});
new TypeIs(类型,选项?)
创建可重用的内容类型匹配器。可选 options 对象接受:
lookup解析简写类型的函数(参见normalize).parameterValue:一个(key: string, value: string) => string函数,在比较之前对配置和传入参数值进行规范化。默认情况下,charset值小写,其他值不变。
每一种 types Array可以是以下类型之一:
- mime类型,如
application/json。 - 带有通配符的mime类型,例如
*/*或*/json或application/*。 - 后缀如
+json. 这可以与通配符结合使用,例如*/vnd+json或application/*+json。 - 配置的简写,例如
multipart或urlencoded。 - 上述任何一个参数也必须匹配,例如
text/html; charset=utf-8。
typeIs.is(值)
检查 content-type 值并返回匹配的第一个配置类型,或 undefined 当没有匹配时。
const isJson = new TypeIs(["application/json", "application/*+json"]);
isJson.is("application/json"); // => 'application/json'
isJson.is("application/vnd.api+json"); // => 'application/*+json'
isJson.is("text/html"); // => undefined
typeIs.request(请求)
根据配置的类型检查请求。如果请求没有正文,即使有 Content-Type 头,然后 undefined 返回。否则它会使用 is 要查看 content-type 头。
// req.headers.content-type = 'application/json'
new TypeIs(["json"]).request(req); // => 'application/json'
new TypeIs(["application/*"]).request(req); // => 'application/*'
new TypeIs(["application/json"]).request(req); // => 'application/json'
new TypeIs(["text/html"]).request(req); // => undefined
hasBody(请求)
如果给定,则返回true request 有一个基于所提供的HTTP头的正文。
主体的大小与主体的大小无关(主体可以是0字节)。 这类似于文件存在的工作原理。如果肉体确实存在,那么 表示有数据要从Node.js请求流中读取。
if (typeis.hasBody(req)) {
// read the body, since there is one
req.on("data", function (chunk) {
// ...
});
}
匹配(预计)
编译类型字符串 expected 转换为与MIME类型匹配的函数。
typeis.match("text/html")("text/html"); // => true
typeis.match("*/html")("text/html"); // => true
typeis.match("text/*")("text/html"); // => true
typeis.match("*/*")("text/html"); // => true
typeis.match("*/*+json")("application/x-custom+json"); // => true
正常化(类型、期权?)
规范化 type 字符串。它通过执行以下操作来工作:
- 如果字符串包含
/,然后作为类型返回。 - 如果字符串以
+(所以它是+suffix速记像+json),然后将其扩展为包含完整的通配符符号*/*+suffix。 - 否则,该字符串将被假定为文件扩展名并返回映射的媒体类型,如果没有映射,则返回原始输入。
默认扩展保持最小:
'json'->'application/json''multipart'->'multipart/*''urlencoded'->'application/x-www-form-urlencoded'
的选项对象 { lookup: (value: string) => string | string[] | undefined } 提供额外的映射,例如 mime.lookup。
例子
示例体解析器
const express = require("express");
const { TypeIs, hasBody } = require("type-is");
const app = express();
const typeIs = new TypeIs(["urlencoded", "json", "multipart"]);
app.use(function bodyParser(req, res, next) {
if (!hasBody(req)) {
return next();
}
switch (typeIs.request(req)) {
case "application/x-www-form-urlencoded":
// parse urlencoded body
throw new Error("implement urlencoded body parsing");
case "application/json":
// parse json body
throw new Error("implement json body parsing");
case "multipart/*":
// parse multipart body
throw new Error("implement multipart body parsing");
default:
// 415 error code
res.statusCode = 415;
res.end();
break;
}
});