带头文件和身份验证的npm请求

Pra*_*mar 15 curl node.js

我正在尝试使用"请求"npm访问API.此API需要标头"content-type"和基本身份验证.这是我到目前为止所做的.

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);
Run Code Online (Sandbox Code Playgroud)

在使用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 "

请建议使用auth和header编码请求的正确方法.


这是我的更新代码

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);
    }
Run Code Online (Sandbox Code Playgroud)

我在控制台中看到"未定义".你能在这帮我吗?

Kat*_*nko 24

这是它对我有用的方式

 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'
     }
 };
Run Code Online (Sandbox Code Playgroud)

  • @Praveen Kumar:在我看来,Katerina的回答是完全正确的,应该接受作为答案。 (2认同)

Ray*_*lha 6

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);
    }
});
Run Code Online (Sandbox Code Playgroud)