Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write headers to http get request

Tags:

http

node.js

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?

like image 619
Alexander Mills Avatar asked Jun 20 '18 07:06

Alexander Mills


2 Answers

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.

like image 179
Terry Lennox Avatar answered Oct 21 '22 10:10

Terry Lennox


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}` }
like image 5
Paul Avatar answered Oct 21 '22 09:10

Paul