node.js 带有标头和身份验证的 npm 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30137231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
npm request with headers and auth
提问by Praveen Kumar
I am trying to access an API using "request" npm. This API requires header "content-type" and a basic authentication. here is what I've done so far.
我正在尝试使用“请求”npm 访问 API。此 API 需要标头“内容类型”和基本身份验证。这是我到目前为止所做的。
var request = require('request');
var options = {
url: 'https://XXX/index.php?/api/V2/get_case/2',
headers: {
'content-type': 'application/json'
},
};
request.get(options, function(error, response, body){
console.log(body);
}
).auth("[email protected]","password",false);
upon executing this using Node , I am getting an error that says invalid username and password. I've validated the same API, authentication and header using CURL with the command below and it gave an expected HTTP response.
使用 Node 执行此操作时,我收到一条错误消息,指出用户名和密码无效。我已经使用 CURL 和下面的命令验证了相同的 API、身份验证和标头,它给出了预期的 HTTP 响应。
curl -X GET -H "content-type: application/json" -u [email protected]:password "https://XXX/index.php?/api/V2/get_case/2"
curl -X GET -H "content-type: application/json" -u [email protected]:password " https://XXX/index.php?/api/V2/get_case/2"
Please suggest the right way to code request with auth and header.
请建议使用身份验证和标头对请求进行编码的正确方法。
Here is my update code
这是我的更新代码
var auth = new Buffer("[email protected]" + ':' + "password").toString('base64');
var req = {
host: 'https://URL',
path: 'index.php?/api/v2/get_case/2',
method: 'GET',
headers: {
Authorization: 'Basic ' + auth,
'Content-Type': 'application/json'
}
};
request(req,callback);
function callback(error, response, body) {
console.log(body);
}
I am seeing 'undefined' in my console. can you help me here?
我在控制台中看到“未定义”。你能帮我吗?
回答by Katerina Pavlenko
Here is how it worked for me
这是它对我的工作方式
var auth = new Buffer(user + ':' + pass).toString('base64');
var req = {
host: 'https://XXX/index.php?/api/V2/get_case/2',
path: path,
method: 'GET',
headers: {
Authorization: 'Basic ' + auth,
'Content-Type': 'application/json'
}
};
回答by Ray Hulha
request(url, {
method: "POST",
auth: {
user: this.user,
pass: this.pass
}
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('body:', body);
} else {
console.log('error', error, response && response.statusCode);
}
});

