带有标头和身份验证的 npm 请求

问题描述 投票:0回答:3

我正在尝试使用“请求”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);

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

curl -X GET -H“内容类型:application/json”-u [电子邮件受保护]:密码“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);
    }

我在控制台中看到“未定义”。你能帮我吗?

node.js curl
3个回答
28
投票

这对我来说是有效的

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

10
投票
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);
    }
});

0
投票
let auth = new Buffer(username + ':' + password).toString('base64');
request(URL, {
    method: 'GET',
    headers: {
        Authorization: 'Basic ' + auth,
        'Content-Type': 'application/json'
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.