本文介绍了如果有基本授权,如何在Node.js中使用http.client的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
按标题,我该怎么做?
这是我的代码:
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
字段.
You have to set the Authorization
field in the header.
在这种情况下,它包含身份验证类型Basic
和在Base64中编码的username:password
组合:
It contains the authentication type Basic
in this case and the username:password
combination which gets encoded in Base64:
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中使用http.client的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!