javascript - 如何使用 Node js 中的 API key 从 REST api 获取数据?

标签 javascript node.js api rest authentication

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

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

我不知道如何在 Node.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."
}

最佳答案

像这样更改您的请求..

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

关于javascript - 如何使用 Node js 中的 API key 从 REST api 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36089492/

相关文章:

node.js - 带有灰尘的 mongo 中的服务器端渲染

javascript - javascript 中是否可以在 if 语句或 switch 中使用 include ?

javascript - jQuery 对话框 - 将变量值从 PHP 传递到 jQuery 函数

javascript - 从 NodeJS 中抛出的字符串获取堆栈跟踪

Python 和 Nameko - GreenSSLSocket 没有公共(public)构造函数。实例由 SSLContext.wrap_socket() 返回。

android - 为 Android 重新创建 Google Maps API

php - 如何获取通过 Youtube API 上传视频的日期?

javascript - "Leave this Page"按钮点击时重定向

javascript - 是否可以在 JavaScript 中重新加载页面后保留变量值而不使用 cookie 和本地存储?

javascript - Nodejs : Issue with async and forEach - Need to wait the async to resolve