Reputation: 13
I am trying to configure my Axios ("axios": "^1.1.3"
) with JWT authentication using TypeScript. I am running into a TS2339 error on some machines (error does not show up on coworkers computer).
TS2339: Property 'Authorization' does not exist on type 'AxiosHeaders | Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders>'. Property 'Authorization' does not exist on type 'AxiosHeaders'.
20 |
21 | if (token) {
22 | req.headers!.Authorization = `Bearer ${token.accessToken}`;
| ^^^^^^^^^^^^^
23 | }
24 | return req;
25 | }, (err) => Promise.reject(err)
Context code:
export const axiosPrivate = axios.create({
baseURL: API_ENDPOINT_PREFIX(),
headers: {'Content-Type': 'application/json'},
withCredentials: true
});
axiosPrivate.interceptors.request.use((req) => {
const token = selectCurrentToken(store.getState());
if (token) {
req.headers!.Authorization = `Bearer ${token.accessToken}`;
}
return req;
}, (err) => Promise.reject(err)
);
This error does not show up on other computers. I want to set the Bearer token and run the application without recieving the error.
Upvotes: 1
Views: 4303
Reputation: 275
This is an easier syntax for anyone facing this issue.
axios.interceptors.request.use(
config => {
config.headers['Authorization'] = `Bearer ${token.accessToken}`;
return config;
},
error => {
return Promise.reject(error);
}
);
For any further reference, check out this link https://blog.logrocket.com/using-axios-set-request-headers/
Upvotes: 0
Reputation: 41
This works for me; you can also try it:
axiosInstance.interceptors.request.use(
async (config) => {
const token = await getItem("jwtToken");
if (config.headers)
(config.headers as AxiosHeaders).set("Authorization", `Bearer ${token}`);
return config;
},
(error) => Promise.reject(error),
);
Upvotes: 4
Reputation: 1702
As mentioned by @xgenem on Github in this issue, the following syntax should fix your TS error
if (token) {
config.headers = { ...config.headers } as AxiosHeaders;
config.headers.set('Authorization', `Bearer ${token.accessToken}`);
}
Upvotes: 0
Reputation: 90
Looks like Axios had a recent release that updates the classes and types around headers: https://github.com/axios/axios/commit/ab77a40e1cf73e76092588b89a3a0acd899bd5bc
You might try "axios": "1.1.3"
(without the caret) in your package.json
and see if that resolves it. If so, your team may want to plan on updating your codebase dependencies to the latest version of axios.
There's an issue posted on Axios' Github about it now: https://github.com/axios/axios/issues/5416
Upvotes: 1