When attempting to set http headers with invalid characters, Nodejs will throw a TypeError.
const http = require("http");
const server = http.createServer((req, res) => {
// Attempting to set a header with invalid characters
res.setHeader("CF-Region", "中文");
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, world!");
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
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'
}
- Use
res.writeHead
instead ofres.setHeader
.
res.writeHead
bypasses the ascii character validation, however, this is not a direct replace because res.writeHead can only be called once before response is sent.
- encode the value via
encodeURIComponent