Using the built in NodeJs fetch client does not have the same return type.
-
I am upgrading my app and going to use the built in http client 'fetch'. I have been using the request library that is now deprecated. I am having an issue with what 'fetch' returns from JsReport. I am getting a string so when 'response.json()''' is called I get error
'Unexpected token '%', "%PDF-1.6\n%"... is not valid JSON'
. When I call the same url with 'request' I get an object. It seems like 'fetch' only returns the content of the body property. Is anyone having a similar issue?request code:
const promise = new Promise<any>((resolve, reject) => { const options = { json: data, uri: 'http://jsreport.innovationind.com/api/report' }; post(options, (err, result) => { if (err) { return reject(err); } resolve(result); }); }); return promise;
fetch code:
try { const response = await fetch('http://jsreport.innovationind.com/api/report', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body:JSON.stringify(data) }); if (response.ok && response.body) { const body = await response.json(); //error occurs here return body; } else { throw new Error('Failed to fetch the report'); } } catch (error: any) { logger.error(error); return Promise.resolve(error); }
-
The response is a binary stream containing the report content and not a json, therefore the
response.json
won't work and fail on json parsing error.I don't know what you want to do with the output afterward, but you can use for example
await response.arrayBuffer()
-
@admin I think I get it now. I am able to recreate what my client was expecting with the following code. It needed a body property with the data and a headers property with a
permanent-link
property. Thanksconst body = await response.text(); const permanentLink = await response.headers.get('permanent-link'); return {data:{body,headers:{'permanent-link':permanentLink}}};