简体   繁体   中英

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

I have a JSON object X

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

I am encoding the above object using btoa() in client-side Javascript

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. I have tried to decode using Buffer , but not getting the result.

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. Received an instance of Object

Could anyone please suggest me a solution?

The result from Buffer.from is an instance of 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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