【问题标题】:npm request with headers and auth带有标头和身份验证的 npm 请求
【发布时间】:2015-07-20 03:51:26
【问题描述】:

我正在尝试使用“请求”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("dummyemail@abc.com","password",false);

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

curl -X GET -H "content-type: application/json" -u dummyemail@abc.com:password "https://XXX/index.php?/api/V2/get_case/2"

请建议使用身份验证和标头对请求进行编码的正确方法。


这是我的更新代码

var auth = new Buffer("dummy@gmail.com" + ':' + "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


    【解决方案1】:
    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);
        }
    });
    

    【讨论】:

      【解决方案2】:

      这对我来说是这样的

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

      【讨论】:

      • 感谢您的回答。这是我对您的建议所做的尝试。
      • @Praveen Kumar:在我看来,Katerina 的回答完全正确,应该被接受为答案
      猜你喜欢
      • 2016-03-15
      • 2017-05-08
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      相关资源
      最近更新 更多