Reputation: 243
I am facing a very confusing problem with converting an image to a base64 string in Node.js
Here is my example code:
app.get('/image', (req, res) => {
ServerAPI.queryViewImage(options).then(image => {
res.render('image', { image: Buffer.from(image, 'binary').toString('base64') });
});
});
So basically, the most important thing is this chunk, where I am converting my image response to base64 string:
{ image: Buffer.from(image, 'binary').toString('base64') }
Actually, I tested my API with Postman and the image was displayed correctly. Then, I converted the image to base64 using online converter and included the code in my html / img src, which worked.
Then I compared base64 code generated by Node.js and online converter from the same API call - obviously, there are differences. Screenshot below:
differences between Node.js response to base64 and image to base64
What I am missing? Why is Node.js is not converting my image response correctly?
//EDIT: Including code of queryViewImage function.
//basically, this function connects to server and returns image response as promise. rp() is from request-promise library
const queryViewImage = (token, siteId, viewId) => {
const options = {
method: 'GET',
url: `${url('sites')}/${siteId}/views/${viewId}/image`,
headers: {
'X-Tableau-Auth': token
}
};
return rp(options)
.then((response) => response)
.catch((err) => err);
}
Upvotes: 0
Views: 681
Reputation: 243
I found a solution. Hopefully someone will use this in future.
So, the request-promise library had some default encoding. To remove it, I added 'encoding' property to options object and set it to null. As in below
const options = {
method: 'GET',
url: `${url('sites')}/${siteId}/views/${viewId}/image`,
headers: {
'X-Tableau-Auth': token
},
encoding: null
};
Upvotes: 2