【问题标题】:How to get data from REST api using an API key in node js?如何使用节点 js 中的 API 密钥从 REST api 获取数据?
【发布时间】:2018-04-06 19:39:38
【问题描述】:

我在我的节点服务器中使用了第 3 方 REST API。第 3 方 API 提供商给了我一个 API 密钥和一个 cURL 中的示例,如下所示:

$ curl -u APIKey@https://xyzsite.com/api/v1/users

我不确定我是如何在节点 js 中做到这一点的。我试过跟随但没有运气。我明白了

var options = {
  host: "xyzsite.com",
  path: "/api/v1/users",
  headers: {
    "Authorization": "Basic " + myAPIKey
  }
};


https.get(options, function(res, error) {
  var body = "";
  res.on('data', function(data) {
    body += data;
  });
  res.on('end', function() {

    console.log(body);
  });
  res.on('error', function(e) {
    console.log(e.message);
  });
});

控制台消息

{
  "message": "No authentication credentials provided."
}

【问题讨论】:

  • 您使用的是什么 API?您没有提供正确的凭据,或者您的请求包含错误。

标签: javascript node.js api rest authentication


【解决方案1】:

像这样更改您的请求..

https.get(myAPIKey + "@https://xyzsite.com/api/v1/users",function(res,error){
  var body = "";
  res.on('data', function(data) {
    body += data;
  });
  res.on('end', function() {

    console.log(body);
  });
  res.on('error', function(e) {
    console.log(e.message);
  });
});

或者,如果你想使用options 对象..

var options={
  host:"xyzsite.com",
  path:"/api/v1/users",
  auth: myAPIKey
};


https.get(options,function(res,error){
  var body = "";
  res.on('data', function(data) {
    body += data;
  });
  res.on('end', function() {

    console.log(body);
  });
  res.on('error', function(e) {
    console.log(e.message);
  });
});

More info on NodeJs https options

【讨论】:

  • 感谢您的回复。但不幸的是,它没有奏效。第一种方法抛出错误:无法确定域名。第二个同样的错误,没有提供身份验证凭据。
  • 是的,我想我必须更多地了解 API 才能确定它为什么不起作用。
猜你喜欢
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
  • 2021-12-11
  • 2016-07-14
  • 2020-05-31
相关资源
最近更新 更多