gpt4 book ai didi

node.js - 将 headers 写入 http get 请求

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:25 31 4
gpt4 key购买 nike

我有以下简单的功能:

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

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

有人知道这是怎么回事吗?如何向请求写入 header ?

最佳答案

您可以简单地作为 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它会发回您的通话详细信息。

关于node.js - 将 headers 写入 http get 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50942750/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com