简体   繁体   English

如何使用节点 js 中的 API 密钥从 REST api 获取数据?

[英]How to get data from REST api using an API key in node js?

I am using a 3rd party REST API in my node server.我在我的节点服务器中使用了第 3 方 REST API。 The 3rd party API provider as given me an API key and an example in cURL as follows:第 3 方 API 提供者给了我一个 API 密钥和 cURL 中的一个示例,如下所示:

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

I am not sure how I do it in node js.我不确定如何在 node js 中做到这一点。 I have tried following but no luck.我试过跟随但没有运气。 I get我得到

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

Console message控制台消息

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

Change your request like this..像这样改变你的要求..

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

Or, if you want to use the options object..或者,如果您想使用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 关于 NodeJs https 选项的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM