我正在与request进行基本身份验证,我会知道如何在普通javascript中进行相同的身份验证。我已经阅读了一些关于Stackoverflow的文章,但是该解决方案不适用于我的代码。正文和res返回未定义。但是,通过请求它可以正常工作。
这是我的请求摘要:
var url = "https://&&&&&&&&.api.&&&&&&&&.com/3.0";
var username = "&&&&&&&&";
var password = "&&&&&&&&";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
request.get( {
url,
headers : {
"Authorization" : auth
}
}, function(error, response, body) {
console.log('body : ', body);
} );
我已经测试了以下解决方案:
1:
var request = http.request({
'url': 'url',
'Authorization': 'anything:password'
},
function(error, res, body) {
console.log('body : ', body);
},
function (response) {
console.log('STATUS: ' + response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.body));
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
})
}
}
request.end();
2:
var url = "&&&&&&&&";
var username = "&&&&&&&&";
var password = "&&&&&&&&";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var http = require('http');
var request = http.request({
url,
headers : {
"Authorization" : auth
}
}, function(error, res) {
console.log('body : ', res);
} );
request.end();
任何提示都很好
答案 0 :(得分:2)
好像您缺少一些响应处理。
var http = require('http');
var url = "https://jsonplaceholder.typicode.com/todos/1";
var username = "test";
var password = "testPass";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var options = {url, auth};
var req = http.request(options, function(res) {
var data = '';
res.on('data', (chunk) => {
console.log(chunk)
data += chunk;
});
res.on('end', () => {
console.log(data);
});
req.on('error', function(error) {
// Error handling here
});
});
req.end();
此外,如果您要使用带有身份验证的请求,这也可能会有所帮助:https://github.com/request/request#http-authentication