Reputation: 392
The backend is sending me a Bearer token inside the response headers and I want to store it inside the redux store as most of the APIs require that token to be sent back inside the headers.
I'm encountering an issue when I'm attempting to save the token from the response because it comes as undefined
.
This is the code that I've got so far:
const onLogin = async () => {
try {
const response = await axiosInstance.post('/api/auth/login', userData);
push('/');
const token = response.headers['Authorization'];
console.log('token', token);
dispatch(userToken(token));
} catch (error: any) {
console.log('Login Error', error.message);
}
};
The login works. I get status code 200 and can also see the token inside the network tab in the console. But if I try to console.log it, it shows as undefined, so I imagine it's also not stored in the redux store.
How can I get that token and save it to the redux store?
Upvotes: 0
Views: 513
Reputation: 844
You need to adjust the CORS on the server to allow the response to expose the header. If the backend is yours you can do something like this in nodejs:
const cors = require('cors');
const corsOptions = {
origin: ["https://www.yourdomain.com"],
exposedHeaders: 'Authorization',
};
app.use(cors(corsOptions));
My source is this blog and also states:
Even though the response header is visible in the browser, you might not have access to those headers through the API for security reasons - because of CORS
Upvotes: 0
Reputation: 11
The issue is coming from the backend, the cors configuration didn't expose "Authorization" header.
Upvotes: 1
Reputation: 130
you can use like:
const { Bearer } = response
if response has Bearer = .......
you can get Bearer
Upvotes: 1