In the backend I'm using Web API CORE, look at the following API:
[HttpGet]
[Route("admins/overview/{id}")]
public IActionResult GetOverview(int id)
{
var item = _adminService.GetOverviewById(id);
Response.Headers.Add("Roles","Admin,User,Editor");// Here we add the roles with its values to Header
Response.Headers.Add("Access-Control-Expose-Headers", "Server,Roles"); // specify the name of headers to access
return Ok(item);
}
Here, I add tow headers : the first one is Roles
with its values and the second one in Access-Control-Expose-Headers
with the name of headers that we want to access them in client-side that they are Server,Roles
By default, only the 6 CORS-safelisted response headers are exposed:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
Now, You can access them in Angular.
You can observe
the full response, to do that you have to pass observe: response
into the options parameter
try this:
isHeader(): Observable<boolean> {
return this.http.get(`${environment.baseUrl}home/login`,{observe: 'response', withCredentials: true}).pipe(
map((response: any) => {
// Here, resp is of type HttpResponse<Sth>.
// You can inspect its headers:
console.log(resp.headers.get('roles')); <-- Get Value of Roles
// And access the body directly, which is typed as MyJsonData as requested.
console.log(resp.body.someField);
})
);
}
And finally this is the result:
server: Kestrel
content-type: application/json; charset=utf-8
roles: Admin,User,Editor
See this-> HttpClient's documentation
and -> complete explanation of Access-Control-Expose-Headers
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…