2015-05-09 63 views
3

我想访问一个API使用“请求”npm。该API需要标头“内容类型”和基本认证。这是我迄今为止所做的。npm请求与标题和身份验证

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

在使用Node执行此操作时,我收到一个错误,指出无效的用户名和密码。我使用下面的命令使用CURL验证了相同的API,身份验证和标头,并给出了预期的HTTP响应。

卷曲-X GET -H “内容类型:应用程序/ JSON” -u [email protected]:密码 “https://XXX/index.php?/api/V2/get_case/2

请建议合适的方式与权威性和头码。


这里是我的更新代码

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

在我的控制台我看到 '未定义'。你能帮我吗?

回答

9

这里是如何工作对我来说

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' 
    } 
}; 
+0

谢谢您的回答。这是我尝试过的建议。 –