I have the following simple function:
export const makeGetRequest = function (token: string, options: any, cb: EVCallback) {
const req = https.get(Object.assign({}, options, {
protocol: 'https:',
hostname: 'registry-1.docker.io',
path: '/v2/ubuntu/manifests/latest'
}),
function (res) {
res.once('error', cb);
res.setEncoding('utf8');
let data = '';
res.on('data', function (d) {
data += d;
});
res.once('end', function () {
try {
const r = JSON.parse(data) as any;
return cb(null, r);
}
catch (err) {
return cb(err);
}
});
});
req.write(`Authorization: Bearer ${token}`);
req.end();
};
I am getting the following error:
Error [ERR_STREAM_WRITE_AFTER_END]: write after end at write_ (_http_outgoing.js:580:17) at ClientRequest.write (_http_outgoing.js:575:10) at Object.exports.makeGetRequest (/home/oleg/WebstormProjects/oresoftware/docker.registry/dist/index.js:61:9) at /home/oleg/WebstormProjects/oresoftware/docker.registry/dist/index.js:67:13 at IncomingMessage. (/home/oleg/WebstormProjects/oresoftware/docker.registry/dist/index.js:22:24) at Object.onceWrapper (events.js:273:13) at IncomingMessage.emit (events.js:187:15) at endReadableNT (_stream_readable.js:1086:12) at process._tickCallback (internal/process/next_tick.js:63:19) Emitted 'error' event at: at writeAfterEndNT (_http_outgoing.js:639:7) at process._tickCallback (internal/process/next_tick.js:63:19)
I also tried:
req.setHeader('Authorization',`Bearer ${token}`);
I got a similar error relating to writing to the request after end.
Anyone know what's going on? How can I write headers to the request?
You can simply pass as part of the HTTP.get request:
const https = require('https');
const options = {
hostname: 'httpbin.org',
path: '/get',
headers: {
Authorization: 'authKey'
}
}
https.get(options, (response) => {
var result = ''
response.on('data', function (chunk) {
result += chunk;
});
response.on('end', function () {
console.log(result);
});
});
BTW: HTTPBin is a useful testing site, you can do http://httpbin.org/get and it will send back the details of your call.
You need to pass the headers as part of your options for the get function.
Right after the path
you can add:
headers: { Authorization: `Bearer ${token}` }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With