将标头写入http get请求

时间:2018-06-20 07:36:43

标签: node.js http

我有以下简单功能:

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();

};

我遇到以下错误:

  

错误[ERR_STREAM_WRITE_AFTER_END]:结束后写入       在write_(_http_outgoing.js:580:17)       在ClientRequest.write(_http_outgoing.js:575:10)       在Object.exports.makeGetRequest(/home/oleg/WebstormProjects/oresoftware/docker.registry/dist/index.js:61:9)       在/home/oleg/WebstormProjects/oresoftware/docker.registry/dist/index.js:67:13       在IncomingMessage。 (/home/oleg/WebstormProjects/oresoftware/docker.registry/dist/index.js:22:24)       在Object.onceWrapper(events.js:273:13)       在IncomingMessage.emit(events.js:187:15)       在endReadableNT(_stream_visible.js:1086:12)       在process._tickCallback(内部/进程/next_tick.js:63:19)在以下位置发出“错误”事件:       在writeAfterEndNT(_http_outgoing.js:639:7)       在process._tickCallback(internal / process / next_tick.js:63:19)

我也尝试过:

 req.setHeader('Authorization',`Bearer ${token}`);

我在结束后写入请求时遇到类似的错误。

任何人都知道发生了什么事吗?如何将标头写入请求?

2 个答案:

答案 0 :(得分:2)

您可以简单地将其作为HTTP.get请求的一部分传递:

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);
    });

});

顺便说一句:HTTPBin是一个有用的测试站点,您可以执行http://httpbin.org/get,它将发送回您的呼叫详细信息。

答案 1 :(得分:1)

您需要将标头作为get函数的选项的一部分传递。

path之后,您可以添加headers: { Authorization: Bearer $ {token}``