8

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?

0

1 Answer 1

11

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.