网站搜索

node.js - 在使用 REST API 将 JSON 保存到 Azure Storage Blob 时,JSON 中缺少花括号


我尝试保存一个包含特殊字符 'ø' 的 JSON。

JSON 是 {"username":"Jøhn"}。

我已经使用这个 API 将 JSON 保存到 Azure Blob ==> https://$ {storageAccountName}.blob.core.windows.net/$ {containerName}/$ {name}$ {sasToken}

保存在 blob 容器中的 json 是 {"username":"Jøhn" (最后一个花括号缺失)。

在 REST API 中使用的头是:'x-ms-blob-type': 'BlockBlob', 'x-ms-date': date, 'x-ms-version': '2016-05-31', 'Content-Type': 'text/plain', 'Content-Length': value.length

代码是:

const date = (new Date()).toUTCString();

const sasToken = await Storage.GenerateSasTokenIfExpired();

const endpoint = `https://${storageAccountName}.blob.core.windows.net/${containerName}/${name}${sasToken}`;

return backOff(() => new Promise((resolve, reject) => {
  request.put({
    'body': value,
    'headers': {
      'x-ms-blob-type': 'BlockBlob',
      'x-ms-date': date,
      'x-ms-version': '2016-05-31',
      'Content-Type': 'text/plain',
      'Content-Length': value.length
    },
    'url': endpoint
  }, function (err, result) {
    if (err) {
      return reject(err);
    }
    if (result.statusCode !== 201) {
      return reject(result.body);
    }
    return resolve(result);
  });
}), AzureBackOff.retryPolicy);

答案#1

你的怀疑是正确的。基本上问题出在包含特殊字符(ø)的字符串的 value.length 上。

当我运行以下代码时:

const value = '{"username":"Jøhn"}';
console.log(value);
console.log('value.length', value.length);//Prints 19
const buffer = Buffer.from(value);
console.log('buffer length', buffer.length);//Prints 20

因为传递的内容长度是19,所以少发送了一个字符,这就是你看到这个问题的原因。

请更改以下代码行:

'Content-Length': value.length

到

'Content-Length': Buffer.from(value).length

那应该能解决问题。