Nodejs request: HPE_INVALID_HEADER_TOKEN
I had the same issue, running the code like this worked for me
nodemon --http-parser=legacy
The solution is this library: https://www.npmjs.com/package/http-parser-js
So to fix your problem:
npm install http-parser-js
Add this code before require('request')
process.binding('http_parser').HTTPParser = require('http-parser-js').HTTPParser;
Had the same error and provided solutions are not working anymore in node v14 and v16.
I ended up using node-libcurl
(with node v16.15.1)
const { Curl } = require('node-libcurl');
const curl = new Curl();
var api_URL = "https://www.......";
curl.setOpt('URL', api_URL);
curl.setOpt('FOLLOWLOCATION', true);
curl.setOpt(Curl.option.HTTPHEADER, ['Content-Type: application/json', 'Authorization: Bearer XYZ']);
curl.on('end', function(statusCode, data, headers) {
// do something with the data you get..
// .....
this.close();
});
curl.on('error', curl.close.bind(curl));
curl.perform();
If you like to see how your Header looks like, add this option:
curl.setOpt(Curl.option.VERBOSE, true);
Node v12 has a new parser that is more strict with header validation, which can cause the same errors, especially with sites using Imperva/Incapsula that include an invalid header in HTTP 1.1 responses.
A temporary solution is to use the --http-parser=legacy
option in node's command line, or in the NODE_OPTIONS
environment variable.
Since v12.15.0
and v10.19.0
you can do this:
http.request(url, { insecureHTTPParser: true })
Additional information can be found here: https://github.com/nodejs/node/issues/27711#issuecomment-584621376
Edit: --http-parser=legacy
is no longer supported in recent versions (including minor versions of v12). A solution for newer node versions is to use --insecure-http-parser
instead.