Axios get access to response header fields
Solution 1
In case of CORS requests, browsers can only access the following response headers by default:
- Cache-Control
- Content-Language
- Content-Type
- Expires
- Last-Modified
- Pragma
If you would like your client app to be able to access other headers, you need to set the Access-Control-Expose-Headers header on the server:
Access-Control-Expose-Headers: Access-Token, Uid
Solution 2
This really helped me, thanks Nick Uraltsev for your answer.
For those of you using nodejs with cors:
...
const cors = require('cors');
const corsOptions = {
exposedHeaders: 'Authorization',
};
app.use(cors(corsOptions));
...
In the case you are sending the response in the way of res.header('Authorization', `Bearer ${token}`).send();
Solution 3
I was facing the same problem. I did this in my WebSecurity.java
, it's about the setExposedHeaders
method in the CORS configuration.
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.setAllowedOrigins(Arrays.asList(FRONT_END_SERVER));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
configuration.setAllowedHeaders(Arrays.asList("X-Requested-With","Origin","Content-Type","Accept","Authorization"));
// This allow us to expose the headers
configuration.setExposedHeaders(Arrays.asList("Access-Control-Allow-Headers", "Authorization, x-xsrf-token, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, " +
"Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
I hope it works.
Solution 4
Faced same problem in asp.net core Hope this helps
public static class CorsConfig
{
public static void AddCorsConfig(this IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.WithExposedHeaders("X-Pagination")
);
});
}
}
Solution 5
According to official docs:
This may help if you want the HTTP headers that the server responded with. All header names are lower cased and can be accessed using the bracket notation. Example: response.headers['content-type']
will give something like: headers: {},
Related videos on Youtube
Comments
-
TWONEKSONE over 2 years
I'm building a frontend app with React and Redux and I'm using axios to perform my requests. I would like to get access to all the fields in the header of the response. In my browser I can inspect the header and I can see that all the fields that I need are present(such as token, uid, etc...), but when I call
const request = axios.post(`${ROOT_URL}/auth/sign_in`, props); request.then((response)=>{ console.log(response.headers); });
I get just
Object {content-type: "application/json; charset=utf-8", cache-control: "max-age=0, private, must-revalidate"}
Here my browser network tab,as you can see all the other fields are present.
Bests.
-
Ben Hare about 8 yearsIf you print out axios.defaults.headers does that give you any of the one's you're missing? Some headers are configured at that level, not at that of each request (see github.com/mzabriskie/axios#global-axios-defaults)
-
TWONEKSONE about 8 yearsIs not it
axios.defaults.headers
for configure the REQUEST header params? I need to access the RESPONSE one. @BenHare -
Daniel B about 7 yearsBTW, what you called request, is not a request. It's a promise for your response. Your request was what you passed to the post() method as arguments.
-
-
TWONEKSONE about 8 yearsMy bad I forgot to expose that fields.
-
CWitty almost 7 yearsIf you are using Rails with Rack-Cors you need to set
expose: ['Access-Token', 'Uid']
on the origin like:resource '*', :headers => :any, :methods => [:get, :post, :put, :patch, :delete, :options, :head], expose: ['Access-Token', 'Uid']
-
adanilev over 5 yearsI don't get it. If they are not exposed, why are the additional headers visible in the browser but not in the axios response?
-
erfling over 5 years@adanilev, browsers allow you to see them for debugging purposes, but prevent you from accessing them through APIs for security reasons. It prevents clients from getting secured credentials from servers, allowing the server to determine what access a client has. TLDR: it's done on purpose for security
-
nircraft about 5 yearsWelcome to SO! Your answer may be correct but at StackOverflow, it is discouraged to post code only answer. Please try to provide an explanation of how your answer solves the original question. please read this on how to Write Better Answer
-
Old Man Walter almost 5 yearsI have this in my NGINX confg file...
'Access-Control-Expose-Headers' 'Authorization, X-Suggested-Filename, content-disposition' always;
Still only seecontent-type: "application/pdf"
really need to pullcontent-disposition
-
Prabin Upreti over 4 yearsIn my grails server app i have set expose headers as cors.expose.headers = ['authorization'] and i am seeing the Access-Control-Expose-Headers : Authorization in my network tab as well. But i am not able to get it from axios response. Here also in @TWONEKSONE question, network tab already contains Access-Control-Expose-Headers : Authorization but why wasn't he able to access the headers? Please help.
-
Thiago Santana over 4 yearsFor those wondering, you could pass an array here too: exposedHeaders: ['Authorization','X-Total-Count']
-
Bi Wu almost 4 yearsI solved it by adding header("Access-Control-Allow-Headers: Authorization, Custom-Header") in PHP back-end.
-
E Ciotti over 3 yearsThanks. Worked in Java Spring
response.addHeader("Access-Control-Expose-Headers", "Access-Token"); response.addHeader("Access-Token","yourToken");
where response is theHttpServletResponse
-
cpinamtz over 3 yearsAt least for Flask CORS, you can also pass a dict where each key is named
CORS_<property>
(in this caseexpose_headers
) and pass it with the desired values in theCORS(app, **cors_config)
statement. See docs here -
LuiKang almost 3 yearsThank you for that. I tried the wildcard '*' , which did'nt work, but using your answer as help it really helped me.