Angular5 Response Header (Content-Disposition) Reading - angular-http

How Can I read Response Header (Content-Disposition)? Please share resolution.
When I check at either Postman or Google Chrome Network tab, I can see 'Content-Disposition' at the response headers section for the HTTP call, but NOT able to read the header parameter at Angular Code.
// Node - Server JS
app.get('/download', function (req, res) {
var file = __dirname + '/db.json';
res.set({
'Content-Type': 'text/plain',
'Content-Disposition': 'attachment; filename=' + req.body.filename
})
res.download(file); // Set disposition and send it.
});
// Angular5 Code
saveFile() {
const headers = new Headers();
headers.append('Accept', 'text/plain');
this.http.get('http://localhost:8090/download', { headers: headers })
.subscribe(
(response => this.saveToFileSystem(response))
);
}
private saveToFileSystem(response) {
const contentDispositionHeader: string = response.headers.get('Content-Disposition'); // <== Getting error here, Not able to read Response Headers
const parts: string[] = contentDispositionHeader.split(';');
const filename = parts[1].split('=')[1];
const blob = new Blob([response._body], { type: 'text/plain' });
saveAs(blob, filename);
}

I have found the solution to this issue. As per Access-Control-Expose-Headers, only default headers would be exposed.
In order to expose 'Content-Disposition', we need to set 'Access-Control-Expose-Headers' header property to either '*' (allow all) or 'Content-Disposition'.
// Node - Server JS
app.get('/download', function (req, res) {
var file = __dirname + '/db.json';
res.set({
'Content-Type': 'text/plain',
'Content-Disposition': 'attachment; filename=' + req.body.filename,
'Access-Control-Expose-Headers': 'Content-Disposition' // <== ** Solution **
})
res.download(file); // Set disposition and send it.
});

It is not the problem with Angular, is the problem with CORS.
If the server does not explicitly allow your code to read the headers, the browser don't allow to read them.
In the server you must add Access-Control-Expose-Headers in the response.
In the response it will be like Access-Control-Expose-Headers:<header_name>,
In asp.net core it can be added while setting up CORS in ConfigureServices method in startup.cs

this solution help me to get the Content-Disposition from response header.
(data)=>{ //the 'data' is response of file data with responseType: ResponseContentType.Blob.
let contentDisposition = data.headers.get('content-disposition');
}

Firstly you need to allow your server to expose these headers. Note that it will show in you browser network tab, regardless if you have these settings. This makes it 'available'.
With C# it would look something like this:
services.AddCors(options => {
options.AddPolicy(AllowSpecificOrigins,
builder => {
builder
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.WithExposedHeaders("Content-Disposition", "downloadFileName");
});
});
When you send your API request to the server ensure that you include the "observe" in you return. See below:
getFile(path: string): Observable<any> {
// Create headers
let headers = new HttpHeaders();
// Create and return request
return this.http.get<Blob>(
`${environment.api_url}${path}`,
{ headers, observe: 'response', responseType: 'blob' as 'json' }
).pipe();
}
Then in your response of your angular on your subscribe you can access your filename like this (the subscribe method is not complete it attaches to a pipe function)
.....
.subscribe((response: HttpResponse<Blob>) => {
const fileName = response.headers.get('content-disposition')
.split(';')[1]
.split('filename')[1]
.split('=')[1]
.trim();
});

Related

Angular 2 POST don't send data to ASP.NET server

I would like to send data from client to ASP.NET MVC server using POST method. Web api action was called, but data haven't been sent to server. When I open Fiddler, i see data.
Here is my code:
Client
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post('http://localhost/app/api/Users/', 'hello', { headers: headers, withCredentials: true })
.subscribe(user => {
console.log(user);
});
Server
[HttpPost]
public void Post([FromBody]string data)
{
//data is null
}
Where is the problem? Thanks for any advices.
The value is not form encoded but that is what you specify in your content-type header. Change the value to this:
'=hello'
Full call
this.http.post('http://localhost/app/api/Users/', '=hello', { headers: headers, withCredentials: true })
.subscribe(user => {
console.log(user);
});
When using application/x-www-form-urlencoded, you have to use formdata:
let data = new FormData();
data.append('data': 'hello');
ASP.NET won't deserialize the body if you don't specify the correct content-type and give clue about the match between the received body and the name of variables.
One possibility is to serialize the body to JSON, with matching variable names, like that :
let model = { data: "Hello" }
let req = new Headers();
req.headers.append('content-type', 'application/json');
let body = JSON.stringify(model);
this.http.post(url, body, req).subscribe(...)

How to get custom response header in angular 2?

I am new to angular 2 and currently working with angular 2.2.1 in which I am successfully able to post request and get success response however when I try to get Authorization header from response I always get null whether I am able to get Content-Type header. Below is my solution so far.
service.ts login method:
login(model: LoginModel) {
let requestUrl = '/someurl';
let requestPayload = JSON.stringify(model);
let headers = this.getHeaders(false); // ... Set all required headers
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.post(requestUrl, requestPayload, options) // ...using post request
//.map((res: Response)) // ...and calling .json() on the response to return data
.subscribe((res: Response) => {
var payload = res.json();
var authorization = res.headers.get('Authorization');
var contentType = res.headers.get('Content-Type');
console.log(payload, contentType, authorization)
});
}
Header Helper
getHeaders(isSecureAPI: boolean) {
let headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' });
if (isSecureAPI) {
headers.append('Authorization', 'GetFromSession');
headers.append('X-UserID', 'GetFromSession');
}
return headers;
}
Fiddler track:
Angular Console Output
So anyone can guide me what I am possibly doing wrong?
Header was allowed but not exposed on CORS server however adding headers.add("Access-Control-Expose-Headers", "Authorization, X-Custom"); on server did the job :)
I've been trying to find a solution and came across this
Let's say I'm using the Microsoft Cors WebAPI 2 Nuget package, and I have the following global configuration in my WebApiConfig.cs:
...
var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(corsAttr);
...
The EnableCorsAttribute constructor accepts a 4th string parameter to globally allow any additional headers:
var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*", "X-Foo, X-Bar, X-Baz");

Ionic 2 - Include Authorization header in all api calls

My Ionic 2 app have few providers and they communicate with a secured API over http, so I have to include an authorization header contains bearer token (which I stored in localstorage) with every request I made.
My current (ugly) implementation is for each function, am appending header like below sample code,
getAccountDetails(accountId: string): Promise<any> {
let url = API_ENDPOINT + 'some-string';
return new Promise(resolve => {
this.userData.hasLoggedIn().then((hasLoggedIn) => {
if (hasLoggedIn) {
this.userData.getUserToken().then((token) => {
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + token);
this.http.post(url, { id: accountId }, { headers: headers }).map(res => res.json()).subscribe(data => {
resolve(data);
});
})
}
})
});
}
As I mentioned above, for each functions now I repeat the same header append code, how can I make it DRY (avoid repeating the same code)?

How to read received headers in Angular 2?

Can some body tell me how to read received headers in Angular 2?
i have mad a request, for login and password, and there should be sent back headers with Token. I need the token for further workaround.
here is part of the code:
sendLogin(username, password) {
let body = JSON.stringify({"username": username, "password": password});
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.post(this.loginUrl, body, options)
.map(res => res.json())
.map((res) => {
if (res.ok) {
// at least how to console.log received headers?
console.log( res.headers); //undefined
this.loggedIn = res.ok;
} return res.ok;
});
};
thank you.
Most of the time such an issue is related to CORS. You need to explicitly enable allowed headers in the response headers.
You're only be able to see the header in the map only if it's enabled by CORS.
Your server needs to return the following in headers:
Access-Control-Allow-Headers: X-SomeHeader

problems with sending jpg over http - node.js

I'm trying to write a simple http web server, that (among other features), can send the client a requested file.
Sending a regular text file/html file works as a charm. The problem is with sending image files.
Here is a part of my code (after parsing the MIME TYPE, and including fs node.js module):
if (MIMEtype == "image") {
console.log('IMAGE');
fs.readFile(path, "binary", function(err,data) {
console.log("Sending to user: ");
console.log('read the file!');
response.body = data;
response.end();
});
} else {
fs.readFile(path, "utf8", function(err,data) {
response.body = data ;
response.end() ;
});
}
Why all I'm getting is a blank page, upon opening http://localhost:<serverPort>/test.jpg?
Here's a complete example on how to send an image with Node.js in the simplest possible way (my example is a gif file, but it can be used with other file/images types):
var http = require('http'),
fs = require('fs'),
util = require('util'),
file_path = __dirname + '/web.gif';
// the file is in the same folder with our app
// create server on port 4000
http.createServer(function(request, response) {
fs.stat(file_path, function(error, stat) {
var rs;
// We specify the content-type and the content-length headers
// important!
response.writeHead(200, {
'Content-Type' : 'image/gif',
'Content-Length' : stat.size
});
rs = fs.createReadStream(file_path);
// pump the file to the response
util.pump(rs, response, function(err) {
if(err) {
throw err;
}
});
});
}).listen(4000);
console.log('Listening on port 4000.');
UPDATE:
util.pump has been deprecated for a while now and you can just use streams to acomplish this:
fs.createReadStream(filePath).pipe(req);

Resources