编写HTTP GET请求的标题

13

我有以下简单函数:

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

};

我遇到了如下错误:

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)

我还尝试了:

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

我遇到了一个类似的错误,与在请求结束后写入有关。

有人知道是怎么回事吗?我该如何向请求中写入标头?

2个回答

31

您可以将其作为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
为什么官方文档没有提到这个问题?https://nodejs.org/api/https.html - 1owk3y

6
你需要将标头作为选项的一部分传递给get函数。
path之后,你可以添加:
headers: { Authorization: `Bearer ${token}` }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接