http.validateHeaderValue(name, value)


在调用 res.setHeader(name, value) 时对提供的 value 执行低层验证。

将非法值作为 value 传入将导致抛出 TypeError

  • 未定义值错误由 code: 'ERR_HTTP_INVALID_HEADER_VALUE' 标识。
  • 无效值字符错误由 code: 'ERR_INVALID_CHAR' 标识。

在将标头传给 HTTP 请求或响应之前,不必使用此方法。 HTTP 模块将自动验证此类标头。

示例:

const { validateHeaderValue } = require('http');

try {
  validateHeaderValue('x-my-header', undefined);
} catch (err) {
  err instanceof TypeError; // --> true
  err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'; // --> true
  err.message; // --> 'Invalid value "undefined" for header "x-my-header"'
}

try {
  validateHeaderValue('x-my-header', 'oʊmɪɡə');
} catch (err) {
  err instanceof TypeError; // --> true
  err.code === 'ERR_INVALID_CHAR'; // --> true
  err.message; // --> 'Invalid character in header content ["x-my-header"]'
}

Performs the low-level validations on the provided value that are done when res.setHeader(name, value) is called.

Passing illegal value as value will result in a TypeError being thrown.

  • Undefined value error is identified by code: 'ERR_HTTP_INVALID_HEADER_VALUE'.
  • Invalid value character error is identified by code: 'ERR_INVALID_CHAR'.

It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers.

Examples:

const { validateHeaderValue } = require('http');

try {
  validateHeaderValue('x-my-header', undefined);
} catch (err) {
  err instanceof TypeError; // --> true
  err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'; // --> true
  err.message; // --> 'Invalid value "undefined" for header "x-my-header"'
}

try {
  validateHeaderValue('x-my-header', 'oʊmɪɡə');
} catch (err) {
  err instanceof TypeError; // --> true
  err.code === 'ERR_INVALID_CHAR'; // --> true
  err.message; // --> 'Invalid character in header content ["x-my-header"]'
}