gpt4 book ai didi

node.js - 如果有基本授权,如何在 Node.js 中使用 http.client

转载 作者:IT老高 更新时间:2023-10-28 21:47:33 25 4
gpt4 key购买 nike

按照标题,我该怎么做?

这是我的代码:

var http = require('http');

// to access this url I need to put basic auth.
var client = http.createClient(80, 'www.example.com');

var request = client.request('GET', '/', {
'host': 'www.example.com'
});
request.end();
request.on('response', function (response) {
console.log('STATUS: ' + response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.headers));
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});

最佳答案

您必须在标题中设置 Authorization 字段。

在这种情况下,它包含身份验证类型 Basic 和以 Base64 编码的 username:password 组合:

var username = 'Test';
var password = '123';
var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
// new Buffer() is deprecated from v6

// auth is: 'Basic VGVzdDoxMjM='

var header = {'Host': 'www.example.com', 'Authorization': auth};
var request = client.request('GET', '/', header);

关于node.js - 如果有基本授权,如何在 Node.js 中使用 http.client,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3905126/

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