Angular 8 get txt file with auth header - ajax

I'm trying to implement a download link for users to download a record in .txt file.
Firstly it was a simple <a> tag
download
I could download the file from server in .txt format. But I found that it does not bring Auth header. So I tried to use a http get method to fetch it.
service.js
getCdrFile(url) {
return this.http.get<any>(`${this.env.service}/service/api/downloadFile?` + url);
}
component.js
downloadFile(url) {
this.service.getCdrFile(url).subscribe(
data => {
console.log(data);
},
error => {
console.log(error);
}
);
}
I can successfully call the API with auth head, then I got nothing happened after I clicked the download button but the txt data displayed in the "response" tab in Chrome developer tool. Also, I got nothing from console.log(data); inside my http request.
Is there anyway I can download the file? thanks!
(and here is my response detail)
# GENERAL
Request URL: http://localhost:8080/service/api/downloadFile?fileType=daily&trsDate=20190918
Request Method: GET
Status Code: 200
Remote Address: 127.0.0.1:8080
Referrer Policy: no-referrer-when-downgrade
# RESPONSE HEADER
Accept-Ranges: bytes
Access-Control-Allow-Origin: *
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Disposition: attachment; filename=20190918.txt
Content-Type: application/json
Date: Wed, 02 Oct 2019 03:51:01 GMT
Expires: 0
Pragma: no-cache
Server: nginx/1.15.2
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

You can create a Blob response and create a blob url with it and download on the fly.
Service:
Modify your service to receive a blob response
getImage() {
return this.httpClient.get(
your_image_link,
{
responseType: 'blob', // <-- add this
headers: {your_headers}
}
);
}
Component:
On click of your link on the page call your service to get the response blob of your file
Create a blob url URL.createObjectUrl method
Create a dummy anchor element assign the blob url and name of the file to download
Trigger a click event on the anchor element
remove the blob url from browser using URL.revokeObjectUrl method
downloadImage() {
this.service.getImage().subscribe(img => {
const url = URL.createObjectURL(img);
const a = document.createElement('a');
a.download = "filename.txt";
a.href = url;
a.click();
URL.revokeObjectURL(url);
});
}
Stackblitz: https://stackblitz.com/edit/angular-kp3saz

You have two ways to download the file from the server.
1:-) Ater getting a response from HTTP call to create base64 and create a dummy anchor tag and download.
2:-) Modify backend response as download response.

Related

What defines jqXHR as "failed"

I have a ajax request to a spring security backend. What happens for some reason is that .then doesn't occur ever. What I found out is that .fail occurs on every request, even though the request goes through, the login on the backend works and it returns a response with status code 200. So what defines a jqXHR as failed and what do I need to add in the response so it works as it should?
Here is my ajax request:
// Creates request object
function makeRequest(method, module, endpoint) {
return req = {
method,
url: serverBaseUrl + module + '/' + endpoint
};
}
// Function to return POST promise
function post (module, endpoint, data) {
let req = makeRequest('POST', module, endpoint);
req.data = data;
return $.ajax(req);
}
And here is the response I get from my spring security setup:
HTTP/1.1 200
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Wed, 28 Mar 2018 01:02:20 GMT
Expires: 0
Pragma: no-cache
Set-Cookie: JSESSIONID=8D6265E912D5DFCF418238F18586AFE1; Path=/; HttpOnly
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
After all my problem was in my $.ajax request. I had a dataType parameter added as application/json. That seems to be not valid. Found it out when i printed the error from the request when it failed. Got the answer from here:
jquery ajax call return JSON parsing error

Returning HTTP Error Status Code with Image Content

I'm working on an API that would return an image. In case any error is encountered in the API, though I can issue a HTTP - 500 response (or similar error codes) with text content or no content at all, I need to be able to return an Image Content with the error represented inside the image itself. In other words, when any error is encountered, I create an image representation of the error text and return the image, with the http status code at as 500 - Internal Server Error. I'm using ASP.net Web API and I'm able to create a HTTP 500 Response with Image content and mime type as "image/jpg".
Http 500 with plain text response:
HTTP/1.1 500 Internal Server Error
Content-Length: 14
Content-Type: text/plain; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Mon, 24 Jul 2017 06:43:55 GMT
Error Occured!
Http 500 with Image Content:
HTTP/1.1 500 Internal Server Error
Content-Length: 622485
Content-Type: image/jpg
Server: Microsoft-HTTPAPI/2.0
Date: Mon, 24 Jul 2017 06:44:56 GMT
<<ImageContent>>
Though it is possible, I need to know if this approach is OK as per the best practices of web API or not. Thanks.
Best-practice ("everybody does it") is to return HTML, with a Content-Type: text/html, even if the request was for an image.
You can refer to this site here
Below you can take look at piece of code from shared link:
var result = new HttpResponseMessage(HttpStatusCode.OK);
String filePath = HostingEnvironment.MapPath("~/Images/HT.jpg");
FileStream fileStream = new FileStream(filePath, FileMode.Open);
Image image = Image.FromStream(fileStream);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Jpeg);
result.Content = new ByteArrayContent(memoryStream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return result;

Parse.com Analytics not showing

I'm trying to connect to Parse.com 's REST-API via NSURLConnection to track AppOpened metadata.
I get 200 OK back from the API and the headers are the same to the cURL headers but my API calls are not being represented in the data browser on Parse.com . Is NSURLConnection doing something silly I don't know of? API response is the same but one request gets represented while the other one isn't.
NSLog output:
<NSHTTPURLResponse: 0x7ff5eb331ca0> { URL: https://api.parse.com/1/events/AppOpened } { status code: 200, headers {
"Access-Control-Allow-Methods" = "*";
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Length" = 3;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sun, 04 Jan 2015 22:42:54 GMT";
Server = "nginx/1.6.0";
"X-Parse-Platform" = G1;
"X-Runtime" = "0.019842";
} }
cURL output:
HTTP/1.1 200 OK
Access-Control-Allow-Methods: *
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Date: Sun, 04 Jan 2015 23:03:51 GMT
Server: nginx/1.6.0
X-Parse-Platform: G1
X-Runtime: 0.012325
Content-Length: 3
Connection: keep-alive
{}
It's the same output. What am I doing wrong? Has anyone experience with this?
Turns out Parse was showing funny API keys the moment I copied them out of the cURL example they provide in their lovely docs. Don't know whose analytics I screwed over but I'm terribly sorry and it wasn't my fault!
Always copy your API keys out of [Your-Parse-App-Name]->Settings->Keys
It probably was just a stupid glitch that happened on the Server.

Please help me understand Ajax request versus Backbone fetch()

My app can currently hit our API with a standard JQuery Ajax GET request and get good data back. CORS has been properly implemented on the remote server as far as I can see. Here are the response headers:
company_client_envelope_id: 88764736-6654-22e4-br344-a1w2239a892d
access-control-allow-headers: X-Requested-With, Cookie, Set-Cookie, Accept, Access-Control
Allow-Credentials, Origin, Content-Type, Request-Id , X-Api-Version, X-Request-Id,Authorization, COMPANY_AUTH_WEB
access-control-expose-headers: Location
response-time: 55
request-id: 88764736-6654-22e4-br344-a1w2239a892d
company_api_version: 0.01.09
server: localhost
transfer-encoding: chunked
connection: close
access-control-allow-credentials: true
date: Sun, 09 Feb 2014 14:44:05 GMT
access-control-allow-origin: *
access-control-allow-methods: GET, POST
content-type: application/json
However, using Backbone and calling the same GET request by using fetch() causes the following CORS error:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I cannot figure out what the difference is. Both requests are running from localhost.
In the case of the AJAX query, the following is being sent as requested by the API guys:
headers: {
"accept":"application/json"
}
And in the case of the model and collection declaration I am sending the headers like so:
MyApp.someCollection = Backbone.Collection.extend(
{
model:MyApp.someModel,
headers: {
'Accept':'application/json',
'withCredentials': 'true'
},
url: MYCOMPANY_GLOBALS.API + '/endpoint'
});
and my fetch is simply:
someCollection.fetch();
===============================
Added in response to: #ddewaele
These are the headers from the network tab:
Request URL:http://api-blah.com:3000/
Request Headers CAUTION: Provisional headers are shown.
Accept:application/json
Cache-Control:no-cache
Origin:http://localhost
Pragma:no-cache
Referer:http://localhost/blah/blah/main.html
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107Safari/537.36
There is no pre-flight or remote headers from the API server:
many thanks,
Wittner
I've recommended to you rewrite Backbone.sync method, because in your app you have some security field for example and other reason.
var oldBackboneSync = Backbone.sync;
// Override Backbone.Sync
Backbone.sync = function (method, model, options) {
if (method) {
if (options.data) {
// properly formats data for back-end to parse
options.data = JSON.stringify(options.data);
}
// transform all delete requests to application/json
options.contentType = 'application/json';
}
return oldBackboneSync.apply(this, [method, model, options]);
}
You can add different headers as you want.

Only in Opera: JSON.parse: Unterminated string

In Opera only I receive "JSON.parse: Unterminated string" when going to http://www.underfashion.nl/babys
The string is indeed unterminated, does not end with "]}.
In the other browsers (IE, FF, Chrome) it works fine and receives the entire string.
The string is very long: 217529 chars. Is that possibly the problem? The other browsers receive 220374 chars ending with "]}
I have tried 3 AJAXways to get the data, all with the same strings as result:
The first:
var value = (function () {
var val = null;
$.ajax({'async': false, 'global': false, 'url': uf_urlsearch,
'success': function (data) { val = data;
alert("Data Loaded: " + data.slice(-100) + "<br/>Numofchars: " + data.length);
}
});
return val;
})();
The second:
$.get(uf_urlsearch, function(data){
alert("Data Loaded: " + data.slice(-100));
});
The third:
uf_XMLHttpProductlist.onreadystatechange=function(){
if (uf_XMLHttpProductlist.readyState==4 && uf_XMLHttpProductlist.status==200){
//Get the returned menu-items in Responsetext, expected to look like this:
...
};//if (uf_XMLHttp.readyState==4 && uf_XMLHttp.status==200){
};//uf_XMLHttp.onreadystatechange=function()
uf_urlsearch = "http://www.underfashion.nl/php/get_productlist.php?"+uf_PHPsearchstring;
uf_XMLHttpProductlist.open("GET",uf_urlsearch,true);
uf_XMLHttpProductlist.send();
};
Anyone see any solution?
Best regards,
To inspect the network activity, Go to Opera Menu -> Tools -> Advanced -> Opera Dragonfly. Then enter the URL in your addressbar.
In the Network Tab you can see the list of resources. Select the XHR button, and you will see the get_productlist.php resource. For what is worth, I didn't have any issue with your Web site. The HTTP Request was:
GET /php/get_productlist.php?afdeling=babys HTTP/1.1
User-Agent: Opera/9.80 (Macintosh; Intel Mac OS X 10.7.4; U; fr) Presto/2.10.289 Version/12.00
Host: www.underfashion.nl
Accept-Language: fr,en;q=0.9,en-US;q=0.8,ja;q=0.7,pt;q=0.6,de;q=0.5,zh-CN;q=0.4,es;q=0.3,it;q=0.2,nl;q=0.1,sv;q=0.1,nb;q=0.1,da;q=0.1,fi;q=0.1,zh-TW;q=0.1,ko;q=0.1,pl;q=0.1,pt-PT;q=0.1,ru;q=0.1,ar;q=0.1,cs;q=0.1,hu;q=0.1,tr;q=0.1,ca;q=0.1,el;q=0.1,he;q=0.1,hr;q=0.1,ro;q=0.1,sk;q=0.1,th;q=0.1,uk;q=0.1
Accept-Encoding: gzip, deflate
Referer: http://www.underfashion.nl/babys
Cookie: JSESSIONID=9ABC3B0357487E01298EBC7A02B5FDCD; __atuvc=1%7C25; __utma=137714676.906129982.1340200451.1340200451.1340200451.1; __utmb=137714676.1.10.1340200451; __utmc=137714676; __utmz=137714676.1340200451.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmv=
Connection: Keep-Alive
X-Requested-With: XMLHttpRequest
Accept: */*
Now the HTTP Response is interesting:
HTTP/1.1 200 OK
Date: Wed, 20 Jun 2012 13:54:11 GMT
Server: Apache/2.2.14 (Ubuntu)
X-Powered-By: PHP/5.3.2-1ubuntu4.15
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 11469
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html
Then the json content. Do you see what is wrong in the HTTP response above? YUP.
Content-Type: text/html
The mime type for JSON is defined in RFC 4627. Please send with JSON content the following mime type.
Content-Type: application/json
That said You are saying that you still have the issue (I don't) on some specific URIs. Could you share which one?

Resources