Fetch Data and turn data into CSV and download - javascript

I have an endpoint I fetch that returns a CSV. I'm trying to export that string as a CSV file on click. The header in the response contains content-dispostion and its content type is 'text/csv'.
How can I do this?
let download = await function(){
let response = await fetch('www.endpointblahblah.com')
//The rest of the function needs to take the string that's returned from the response and export as a CSV file by downloading it.
}
Turning the response into JSON throws an error. It should absolutely do this because a JSON object is not returned, it is text.
Thanks in advance.

Related

How should I use fetch with 206 partial (json) content

I have a backend that returns large files as chunks of 206 partial content. I had logic:
fetch(url, query)
.then((resp)=>resp.json())
.then(...)
but surpricingly the code fails because the full json object does not get returned by the server.
Is there some commonly used library to solve this (monkeypatch fetch) or should I write a service-worker or a proxy for this? Why does the default browser fetch not support fetching the full object?
It's not surprising that JSON parsing fails on a partial object. fetch is just going to fetch what you ask it to (well, it follows redirects), so if the query has options for requesting a partial response, that's what you'll get.
You can build up the JSON string until you have the full response to parse, something along these lines:
async function getAll() {
// Start with a blank string
let json = "";
do {
// Get this chunk
const resp = await fetch(url, /*...query for next chunk...*/);
if (!resp.ok && resp.status !== 206) {
throw new Error(`HTTP error ${resp.status}`);
}
// Read this chunk as text and append it to the JSON
json += await resp.text();
} while (resp.status === 206);
return JSON.parse(json);
}
Obviously, that's a rough sketch, you'll need to handle the Range header, etc.
That code also requests each chunk in series, waiting for the chunk to arrive before requesting the next. If you know in advance what the chunk size is, you might be able to parallelize it, though it'll be more complicated with chunks possibly arriving out of sequence, etc.
It also assumes the server doesn't throw you a curveball, like giving you a wider range than you asked for that overlaps what you've already received. If that's a genuine concern, you'll need to add logic for it.

How to send array of files as well as json data using axios in React FE and Flask BE?

so as the title explains, I am trying to send both JSON data and an array of files using Axios to my Flask BE server. I am not sure where the problem lies, whether it is in FE or BE, but I cannot seem to send the files. I am trying to send it in a FormData object but if I try to send the array of files together, it shows:
[object File, object File, ...]
When I send them individually, it sends as binary which is what I want. But I cannot send binary data in the array.
If possible, please let me know how I can send it and read it in my Flask server in BE.
EDIT:
let formData = new FormData();
formData.append('data', JSON.stringify(data));
const files = data?.additional_document;
if (Array.isArray(files )) {
const arrayKey = `additionalFiles`;
files.forEach(v => {
formData.append(arrayKey, v);
});
}
dispatch(apiCallToBackEnd(formData, (res) => getPDF(res)));

parsing json string to angular object from http get

I want to parsing this response from http get and display the value into a detail modal but I dont know how to parse it. I have using arc to show me the response of my http get,here is my image of my response using arc.
here is my.js file
$http.get('.....a='+$scope.month).then(function(response){
$scope.coba = response.data;
Use JSON.stringify(response.data) or angular.toJson(response.data), it will parse the http response into JSON.
If it is failing, means your response is not exact JSON

How to read RAW JSON in Angular JS from HTTP get method, when response type is arraybuffer?

I am trying to read ByteArray to show PDF form Java into Angular JS using
method : 'GET'
url : '',
cache : isCache||false,
responseType: 'arraybuffer'
This is working fine when everything okay.
But when I throw an exception with some proper JSON and marking HTTP Status as bad request, I can't read JSON response even after changing config to respone.config.responseType='application/json'.
It showing only empty ArrayBuffer {} on response.data.
But important thing here is, I can see JSON response in google chrome developer tool request.
I googled, searched on stack overflow but didn't find much.
Below lines added later
I am adding response object picture and data received pic from chrome network connection.
First Image : Response object from error function of angular JS.
Second Image - Server returning proper JSON message
Third Image - Request and Response Header pics
Only problem I am facing is not able read data of response as I set response type to arraybuffer
Instead of expecting arraybuffer why not expect application/json all the time, then when you return your data that's supposed to create your pdf, do a base64 of the data, put it in a json object and return it to the client
Even when you throw an exception you still expect JSON. Your response from server side could be something like:
{
responseCode: // your response code according to whether the request is success or not,
responseMessage: // success or fail
data: // your base64 encoded pdf data(the data that if the request is successful will be returned), note it will be returned as a normal string
} // I'm hoping you know how to base64 encode data
Then in your client side(Javascript), perform an if
if(data.responseCode == //errorCode) {
alert(data.responseMessage);
} else {
// Unpack data
var myPdfData = // base64 decode(data.data)
// Do logic to create and open/download file
}
You don't even need to decode the data, you just create a blob object, then trigger a download from the blob
If the responsetype is arraybuffer, to view it, you should convert it into a blob and create a objectUrl from that blob, and the download it or open in a new tab/browser window to view it.
Js:
$http.get('your/api/url').then(function(response) {
var blob = new Blob([response.data], { type: 'application/pdf' });
var downloadUrl = URL.createObjectURL(blob);
$timeout(function () {
var link = document.createElement('a');
link.download = 'SOME_FILE_NAME'+ '.pdf';
link.href = downloadUrl;
link.click();
}, 100);
}, function(errorResponse){
alert(errorResponse.error.message);
});

How to receive Yaml content in an AJAX call?

In my application, there is an endpoint that sends me the raw contents of a Yaml file in response to an AJAX call. I want to display them as they are in UI. The console throws an obvious error, which is for invalid JSON. How would I do it?
Update:
This is the snippet used for reading the file and sending the response.
filename = __file__ # Select your file here.
wrapper = FileWrapper(file(filename))
response = HttpResponse(wrapper, content_type='text/plain')
response['Content-Length'] = os.path.getsize(filename)
return response
Is there a way I could form a dictionary there with the contents of the file and then send the response?
From server, use jsonify on the raw content, pack it and ship it over to client.
repacked_json = json.dumps(raw_yaml_data)
json_obj = json.loads(repacked_json)
return jsonify(result = json_obj)

Categories