Reputation: 41
I'm working on React Native, in which the axios returns post details from my express api. I use jwt to authenticate user request. The JWT token is in state variable and it is passed to header authorization value. But it works only on first load, When I try to reload the app it shows [AxiosError: Request failed with status code 401] If I try to add data to axios it return Network error. I confirmed my API is fine through Postman, It works fine and returns data. To recheck again, I tried to hard coded to header value, it works fine. But If I pass from state or context variable it throws the 401 error. Again checked with CORS and everything on Express it is fine. I don't know what's happening. Help me with it.
BASE_API_URL = http://192.168.1.2:3000 The above URL runs Express
With state variable it dosen't work
const fetchPosts = async () => {
//console.log(userGlobalToken)
await axios({
method: 'GET',
url: `${BASE_API_URL}/posts/all`,
headers: {
'Get-Auth': userJwtToken
}
})
.then((response) => {
setPostsData(response.data)
})
.catch((err) => console.log(err))
.finally(() => {
setPostLoading(false)
setRefreshing(false)
})
}
This works fine!
const fetchPosts = async () => {
//console.log(userGlobalToken)
await axios({
method: 'GET',
url: `${BASE_API_URL}/posts/all`,
headers: {
'Get-Auth': "<jwt token here>"
}
})
.then((response) => {
setPostsData(response.data)
})
.catch((err) => console.log(err))
.finally(() => {
setPostLoading(false)
setRefreshing(false)
})
}
If you still think it is the problem with express, I checked with AJAX in normal web it worked fine. I console logged to check if the token exist in state variable and it is set. I also checked with other axios requests in which without authorization it throws network error or 404.
Thanks in advance!
Upvotes: 0
Views: 611
Reputation: 32
401 error : expired or invalid your userJwtToken. 401 is "Unauthorized". after along what time your authurization auto code change ?
Upvotes: 0