Reputation: 167
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?
Upvotes: 8
Views: 16441
Reputation: 6898
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());
Upvotes: 11