NodeJS - https - TypeError [ERR_INVALID_HTTP_TOKEN]: Header name must be a valid HTTP token ["Accept​"]

Now this is crazy, but you have an extra character in your "Accept" string. If you run

console.log('Accept​'.charCodeAt(6)) // prints 8203

(You have to run it with your copy of "Accept" from your question, which I assume is copy-pasted from elsewhere)

Unicode 8203 is zero width space, hence it's not visible to us humans :)


By the way, initially i've discovered the character by copy-pasting into Node REPL and noticing a "square" in console output after getting the error.

I've then tried copy-pasting your code into my IntelliJ editor, and was pleasantly surprised to see this warning:

enter image description here


hlfrmn already found this tricky error and gave the correct answer, just in case anyone else is interested:

Starting from version 14.3.0 Node's http module will perform validateHeaderName and validateHeaderValue on each Key-Value pair you specify in your request options headers.

So if you do

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

try {
    const options = {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Accept​': 'application/json',
        }
    };
    for (const header in options.headers) {
        validateHeaderName(header);
    }

} catch (err) {
    console.log(err);
}

the mentioned error will be printed:

TypeError [ERR_INVALID_HTTP_TOKEN]: Header name must be a valid HTTP token ["Accept​"] will be printed from the catch block.