First, you import React and Axios so that both can be used in the component. Then you hook into the componentDidMount lifecycle hook and perform a GET request. You use axios. get(url) with a URL from an API endpoint to get a promise which returns a response object.
When you are using the Axios library and to pass custom headers, you need to construct headers as an object with the key name 'headers'. The 'headers' key should contain an object, here it is Content-Type and Authorization .
In case of CORS requests, browsers can only access the following response headers by default:
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
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();
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.
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")
);
});
}
}
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: {},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With