Skip to content

Instantly share code, notes, and snippets.

@kevinxh
Created March 25, 2024 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinxh/bc95c9353d902b00720a77d078e07b5c to your computer and use it in GitHub Desktop.
Save kevinxh/bc95c9353d902b00720a77d078e07b5c to your computer and use it in GitHub Desktop.
Node.js invalid http header demo

Nodejs invalid http header error

When attempting to set http headers with invalid characters, Nodejs will throw a TypeError.

node:_http_outgoing:628
    throw new ERR_INVALID_CHAR('header content', name);
    ^

TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["CF-Region"]
    at ServerResponse.setHeader (node:_http_outgoing:651:3)
    at Server.<anonymous> (/Users/kevin.he/dev/nodehttpheader/index.js:5:7)
    at Server.emit (node:events:517:28)
    at parserOnIncoming (node:_http_server:1107:12)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17) {
  code: 'ERR_INVALID_CHAR'
}
const http = require("http");
const server = http.createServer((req, res) => {
try {
// Attempting to set a header with invalid characters
res.setHeader("CF-Region", "中文");
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, world!");
} catch (error) {
console.error("Failed to set header:", error.message);
res.writeHead(500, { "Content-Type": "text/plain" });
res.end(error.message);
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment