【问题标题】:Authentication in header with REST API使用 REST API 在标头中进行身份验证
【发布时间】:2022-03-09 13:20:43
【问题描述】:

我是编码新手,并尝试在 Javascript 中使用我的第一个 API。我在弄清楚在哪里填充 API 密钥和标头时遇到了一些麻烦。它是一个 POST,用于向 IOT 设备发送小消息。引用为here,标头引用为here

这是我所拥有的,但我已将我的 API 密钥替换为通用密钥。

request.open('POST', 'https://dashboard.hologram.io/api/1/devices/messages');


request.setRequestHeader('Content-Type', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'deviceid': [storedDeviceID],
  'protocol': 'TCP',
  'port': 80,
  'data': 'Hello world!',
  'base64data': 'SGVsbG8gd29ybGQhCg=='
};

request.send(JSON.stringify(body));

我非常感谢任何帮助。谢谢。

【问题讨论】:

标签: rest http post header


【解决方案1】:

Hologram 提供了一个 API Key,您需要先将其编码为 base64 格式,然后您才能在您的程序中使用它。

所以您可以访问base64encode 或任何其他转换网站(您也可以通过编程方式对其进行编码)然后您必须在那里输入 -

apikey:YOUR_API_KEY

然后将其编码为 base64 格式,类似于

ABCDEFGHIJKLMNOpQrstUVW==

复制它,并在您的程序中使用它。下面是一个使用 Javascript Fetch API 的示例 -

var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic ABCDEFGHIJKLMNOpQrstUVW==");

var requestOptions = {
  method: 'GET',
  headers: myHeaders,
  redirect: 'follow'
};

fetch("https://dashboard.hologram.io/api/1/links/cellular", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多