首页 > 解决方案 > 如何使用@c8y/client 库

问题描述

我正在为 typescript 测试新的 @c8y/client 库。

我有一个非常简单的代码:

import {
  Client
} from '@c8y/client';
//const baseUrl = 'https://bismark1.cumulocity.com/';
const baseUrl = 'https://demos.cumulocity.com/';
const tenant = 'bismark1';
const user = '...';
const password = '.....';


(async() => {
  console.log('authentication to c8y server')
  const client = await Client.authenticate({
    user,
    password,
    tenant
  }, baseUrl);

  console.log('result from authetication', client)
  const {
    data,
    paging
  } = await client.inventory.list();
  console.log('result from inventory ', data)

  // data = first page of inventory
  const nextPage = await paging.next();
  // nextPage.data = second page of inventory

  const managedObjId: number = 1;

  (async() => {
    const {
      data,
      res
    } = await client.inventory.detail(managedObjId);
    console.log(data)
  })();

})();

当我运行从 .ts 文件编译的 .js 时,我得到以下响应:

authentication to c8y server

然后执行停止。

线

console.log('result from authetication', client)

永远不会被调用。似乎在身份验证过程中失败了,并且没有显示错误。

我做错了什么?

谢谢。

标签: cumulocity

解决方案


第一个问题可能是CORS。如果您想从不同的域请求,则需要启用它。以下是如何在 Cumulocity 中执行此操作的指南:

在“访问控制”下,管理员可以在 Cumulocity API 上启用跨域资源共享或“CORS”。

第二个问题可能是您没有从本地开发服务器运行它。我主要使用这个来自 npm 的 http-server来快速测试脚本。您可以通过以下方式使用它:

$ npm install http-server -g
$ http-server

如果这一切都没有帮助您可以尝试捕获客户端以查看它抛出的错误:

try {
  const client = await Client.authenticate({
    user,
    password,
    tenant
  }, baseUrl);
} catch(ex) {
 console.log(ex);
}

该异常可能会告诉您更多有关您的代码有什么问题或客户端中是否存在错误的信息。


推荐阅读