简体   繁体   English

如何在节点js中解码base64编码的json object字符串

[英]How to decode base64-encoded json object string in node js

I have a JSON object X我有一个 JSON object X

var X = {
  'a': 'A',
  'b': 'B'
}

I am encoding the above object using btoa() in client-side Javascript我在客户端 Javascript 中使用btoa()对上述 object 进行编码

var getEncryptedPayload = function(payload) { // payload is a JSON object
  payload = JSON.stringify(payload)
  payload = window.btoa(payload)
  return payload;
}

I want to decode the above encoded string in nodejs.我想在nodejs中解码上面的编码字符串。 I have tried to decode using Buffer , but not getting the result.我尝试使用Buffer进行解码,但没有得到结果。

var getRequestBody = function(request) {
    const encodedRequestBody = request.body;
    const decodedRequestBodyString = Buffer.from(encodedRequestBody, "base64");
    const requestBodyObject = JSON.parse(decodedRequestBodyString);
    return requestBodyObject;
}

But, the above code is throwing an error -但是,上面的代码抛出了一个错误——

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. TypeError [ERR_INVALID_ARG_TYPE]:第一个参数必须是字符串类型或 Buffer、ArrayBuffer 或 Array 的实例或类似 Array 的 Object。 Received an instance of Object收到Object的实例

Could anyone please suggest me a solution?谁能给我建议一个解决方案?

The result from Buffer.from is an instance of Buffer . Buffer.from的结果是Buffer的一个实例。 To transform that buffer instance into a string that can be used in JSON.parse the code needs to invoke Buffer.toString first to make it work要将缓冲区实例转换为可在JSON.parse中使用的字符串,代码需要首先调用Buffer.toString以使其工作

const requestBodyObject = JSON.parse(decodedRequestBodyString.toString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM