I want to add an authorization to header, I've already assign to header before like in the code below
const axiosIns = axios.create({
baseURL: 'http:$$$$$$$$$$/api/app',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
Then I added interceptor and assigned token to authorization header
axiosIns.interceptors.request.use(async config => {
const accessToken = await authService.getAccessToken()
config.headers.Authorization = `Bearer ${accessToken}`
return config
})
but typescript put red line below config.headers says Object is possibly 'undefined'
CodePudding user response:
The error message "Object is possibly 'undefined'" is indicating that the TypeScript compiler is not sure if the "config.headers" object is defined or not. This can happen if the "config" object passed to the request interceptor does not have a "headers" property. To fix this, you can add a check for the "headers" property before trying to access it.
You can add a check to ensure the headers object is defined before trying to add the Authorization header.
axiosIns.interceptors.request.use(async config => {
const accessToken = await authService.getAccessToken()
if (config.headers) {
config.headers.Authorization = `Bearer ${accessToken}`
}
return config
});
This way, if the headers property is undefined, you will skip the assignment and not get the error.
CodePudding user response:
axiosInstance.interceptors.request.use((config: AxiosRequestConfig) => {
config.headers['Authorization'] = auth;
return config
})