javascript - 尝试从 Visual Studio 代码连接到 Azure 数字孪生:DefaultAzureCredential(); .getToken 错误
问题描述
我正在尝试使用适用于 Azure 数字孪生的 Javascript API 从 Visual Studio Code 连接到 Azure Digital wins 实例。
我跑了npm install @azure/identity
,而且npm install @azure/digital-twins-core
。
az login
我可以使用VS Code 中的 Powershell 终端登录到 Azure 门户。它找到我的帐户和订阅并登录。
az account get-access-token --output json
返回我的令牌。
这是我要运行的代码。它应该在 Azure 数字孪生实例中创建两个模型:
const { DefaultAzureCredential } = require("@azure/identity");
const { DigitalTwinsClient } = require("@azure/digital-twins-core");
const { v4 } = require("uuid");
const { inspect } = require("util");
async function main() {
const modelId = `dtmi:model_${v4()
.split("-")
.join("")};1`;
const componentId = `dtmi:component_${v4()
.split("-")
.join("")};1`;
const digitalTwinId = `digitalTwin-${v4()}`;
const temporaryComponent = {
"@id": componentId,
"@type": "Interface",
"@context": "dtmi:dtdl:context;2",
displayName: "Component1",
contents: [
{
"@type": "Property",
name: "ComponentProp1",
schema: "string"
}
]
};
const temporaryModel = {
"@id": modelId,
"@type": "Interface",
"@context": "dtmi:dtdl:context;2",
displayName: "TempModel",
contents: [
{
"@type": "Property",
name: "Prop1",
schema: "double"
},
{
"@type": "Component",
name: "Component1",
schema: componentId
}
]
};
const temporaryTwin = {
$dtId: digitalTwinId,
$metadata: {
$model: modelId
},
Prop1: 42,
Component1: {
$metadata: {},
ComponentProp1: "value1"
}
};
// AZURE_DIGITALTWINS_URL: The URL to your Azure Digital Twins instance
const url = 'https://ParADIM-ADT-Dev.api.wcus.digitaltwins.azure.net';
if (url === undefined) {
throw new Error("Required environment variable AZURE_DIGITALTWINS_URL is not set.");
}
// DefaultAzureCredential is provided by @azure/identity. It supports
// different authentication mechanisms and determines the appropriate
// credential type based of the environment it is executing in. See
// https://www.npmjs.com/package/@azure/identity for more information on
// authenticating with DefaultAzureCredential or other implementations of
// TokenCredential.
const credential = new DefaultAzureCredential();
const serviceClient = new DigitalTwinsClient(url, credential);
// Create models
const newModels = [temporaryComponent, temporaryModel];
const models = await serviceClient.createModels(newModels);
//console.log(`Created Models:`);
//console.log(inspect(models));
}
main().catch((err) => {
console.log("error code: ", err.code);
console.log("error message: ", err.message);
console.log("error stack: ", err.stack);
});
这是我得到的错误:
C:\Program Files\nodejs\node.exe .\index.js
error code: undefined
error message: Unexpected end of JSON input
error stack: Error: Unexpected end of JSON input
at AzureCliCredential.getToken (c:\ADTProject\node_modules\@azure\identity\dist\index.js:1529:27)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async DefaultAzureCredential.getToken (c:\ADTProject\node_modules\@azure\identity\dist\index.js:1358:25)
因此,JSON 输入意外结束。这个错误来自@azure\identity\dist\index.js
哪个是azure\identity
包的一部分,所以不是我写的代码。我使用的代码来自教程,并且 JSON 是兼容的。getToken
似乎执行该功能时出错。
任何帮助表示赞赏!我在这个问题上碰壁了!
解决方案
从文档中提取代码时,查看错误跟踪它无法从指定凭据检索令牌,这可能是我们如何传递它的问题。下面是我们通常在 JavaScript 中的连接方式:
const client = new SecretClient(keyVaultUrl, new DefaultAzureCredential());
下面是与 Cosmos 和存储通信的示例代码:
import { SecretClient } from '@azure/keyvault-secrets';
import { DefaultAzureCredential } from '@azure/identity';
import { CosmosClient } from '@azure/cosmos';
const keyVaultUrl = process.env('APP_KEY_VAULT_URI');
const credential = new DefaultAzureCredential();
let storageClient;
let cosmosClient;
async function configureClients() {
const kvClient = new SecretClient(keyVaultUrl, credential);
const storageUri = await client.getSecret('storageUri');
const cosmosDbConnectionString = await client.getSecret('cosmosDb');
cosmosClient = new CosmosClient(cosmosDbConnectonString);
storageClient = new BlobServiceClient(storageUri, credential);
}
有关环境变量、设置 keyvault 的更多信息,请参阅 azure sdk博客以了解身份验证
推荐阅读
- python - 如何在python中执行去重?
- python - Python Pandas:计算每行每行的中位数(如重叠组)
- python - 我如何通过相似性知道句子中包含的特定字符串?
- wordpress - 功能 wpb_admin_account 使 wp-admin 给我“无法访问此站点”
- python - Pandas 中的字典错误?
- python - 'AttributeError: 'tuple' object has no attribute 'lower'' - 为什么 '.lower()' 方法在 Python 中不起作用?
- java - 如何垂直连接多列字符串?
- entity-framework - dotnet ef 迁移添加 InitialCreate 缺少项目参考
- sql - 在空间表中查找城市之间的距离
- reactjs - 试图以反应钩子形式在 onBlur 调用一个函数