I've created a small project with a node back-end and react front-end to fetch the data through REST calls. I used Axios library, but when I pass the headers with it I keep getting an error saying:
Failed to load resource: the server responded with a status of 401 (Unauthorized).
I found out two methods and both did not work. They are:
export const getUsersDetails=()=>{
console.log('calling');
return (dispatch) => {
return axios.get('http://localhost:3030/users',{headers: { "Authorization": localStorage.getItem('jwtToken') }}).then((data)=>{
console.log('data comming',data);
dispatch(getUsersData(data));
}).catch((error)=>{
console.log('error comming',error);
dispatch(errorgetUsersData(error));
});
};
}
and
axios.defaults.headers.common['Authorization'] = localStorage.getItem('jwtToken');
But When I use postman I am getting the required data from the backend. Any particular reason why I keep getting this Unauthorized error?.
You need to concatenate 'Bearer ' before the token, like this:
axios.defaults.headers.common['Authorization'] =
'Bearer ' + localStorage.getItem('jwtToken');
Related
I am using Axios library to retrieve Auth0 access tokens.
const { data, status, statusText } = await axios.post( https:auth0.url,
body,
{ headers: { "content-type": "application/x-www-form-urlencoded" } });
`
The issue i have is when i am using Axios 1.1.3 to retrieve access-tokens from Auth0 its giving me a proper response.
But when i update the library to 1.2.0 and higher everything breaks. I am getting a response for the same code as raw data
/#����W�{��bhu�E
:U�ȦG>SQ��6�y:90��w>B��� f�4:cA�P��V/����)��v%�_P�ɳ���ꑄ=lb���-F��zh�^X
��N�ˠ��G�
o����W(�Žx>�͔{�5*�������I������`�
���fA\��x~KS[
j��p�Ӌ<���u�qog�.)0G�FI/��R��OԽ�sm�ԝ{X�vV��s$i���2p`� �h�x_Ц��Z�u�9�X�d���B+P���l �m�h�Y��2���ԙ2
��Wx0K
� �Y2IX�d�����P�֎NЂu�qo���f".AJ��+���K枖0�
The stranger part is when i try to use the same code to get the result of an open source api.
const results = await axios.post("www.7timer.info/bin/api.pl?lon=113.17&lat=23.09&product=astro&output=json",
{ headers: { "content-type": "application/x-www-form-urlencoded" } });
I am getting a correct response.
I believe i am only getting this response when i am receiving a token from Auth0. Atleast in my use case
The error i am receiving when i call Auth0 to get tokens is
cause: Error: unexpected end of file
at BrotliDecoder.zlibOnError [as onerror] (node:zlib:189:17) {
errno: -5,
code: 'Z_BUF_ERROR'
}
Is anyone else facing the same issue?
bench-vue Thank you for your sample code. I had to add 'Accept-Encoding' in the request header to receive the tokens. Thank you for your help
I'm using custom tokens and firebase auth. I'm successfully logging in users with email & password and storing the accessToken and refresh tokens. When I go to use the refresh token to get a new access token I'm getting a 401 error. When I try the same post link I'm using in a chrome extension based plugin (for testing REST API's) - the request is successful and I get the desired response. Though with my code in expo & react native I get just a plain, unhelpful 401 error.
My code is as follows:
const headers = {
'Authorization': `Bearer ${accessToken}`
}
const data ={
grant_type : "refresh_token",
refresh_token : refreshToken
}
await axios.post(urlTest, data, {
headers: headers
})
.then((response) => {
console.log("Success! ", response)
})
.catch((error : Error) => {
console.error(error.name, error.message);
})
Not sure what I'm doing wrong here. Maybe a cors issue? A fresh pair of eyes would be welcome.
Thanks!
Seems it might have been a CORS issue. Changed where I was hosting the code to handle posting and getting new access token. Works a treat now.
I am trying to get a long lived access token from facebook... according to the documentation, I need to fetch from the server side for security. If I fetch from the client side it works fine - but I should follow the guidelines.. Here is what I am doing - can you tell me why I get the server side error "Reference error: fetch is not defined"?
First I created a route from the front end to request the long lived token. To get the long lived token I need to use the short lived token so I send the short lived token in the req params. The variable userAccessTokenShort is valid and defined.
const newLongLivedUserAccessToken = await fetch(`/api/autoquotegenerators/longLivedUserToken/${userAccessTokenShort}`, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json; charset=UTF-8",
},
})
const newLongUserTokenRes = await newLongLivedUserAccessToken.json()
console.log(newLongUserTokenRes)
Then, on my express server, I made a route that handles the fetch request to the Facebook Graph API. This is where I get the reference error.
//Get Long Lived User Access Token on Backend /express route
router.get('/longLivedUserToken/:shortLived', (req, res) => {
try {
const getLongToken = fetch(`https://graph.facebook.com/v7.0/oauth/access_token?grant_type=fb_exchange_token&client_id=#############&client_secret=################&fb_exchange_token=${req.params.shortLived}`)
.then(token => res.send(token))
} catch (error) {
console.log(error)
}
})
If all goes well, the new token should be sent back to the client.
Thanks for your help!
There is no fetch() function built into node.js. If you want something that looks pretty much like fetch() in the browser, you can look at the node-fetch module in NPM.
Or, there are lots of modules you can choose from in node.js. My favorite is got().
FYI, the built-in interface for fetching http requests is http.request() or http.get(), but they are lower level and require more lines of code to do something simple than any of the above named modules.
I'm developing React Native application which is connected to Web API written in ASP.NET Core 2.1. I'm trying to make GET request to my secured API's endpoint, but it doesn't work both with fetch and axios.
Noteworthy is fact, when I make request to unsecured (marked as AllowAnonymous) endpoint, everything works fine.
I'm passing following header 'Authorization' : 'Bearer ' + MY_TOKEN
When I tried to use axios, then it returned HTTP 401. When using fetch it returns HTTP 500.
const url = `${baseUrl}/api/cars/get`
fetch(url, {
headers: new Headers({
Authorization: "Bearer <MY_TOKEN_HERE>"
}), method: "GET"
})
I'm sure the token is valid because I am able to get data from API with Postman and with .NET Core console application client.
Is there any way to get the data from secured API's endpoint?
I solved the issue with just one line of code.
axios.defaults.headers.common['Authorization'] = `Bearer ${TOKEN}`
Then I am able to invoke the get request.
const url = `${baseUrl}/api/values`;
axios.get(url)
.then(data => {
console.log(data);
})
.catch(error => {
})
Hope it helps someone who will have such issue in the future.
I am using fetch in React Native in order to make a call to my API, however, it only works 75% of the time.
When my request doesn't work I get this :
TypeError: Network request failed
or
SyntaxError: Unexpected token < in JSON at position 0
fetch('http://localhost/vision.php', {
method: 'POST',
headers: {
'Accept': 'application.json',
'Content-Type': 'application.json',
},
body: JSON.stringify({
key: 'Mon paramètre'
})
})
.then((data) => data.json())
.then((dataJson) => {
console.log(dataJson.message);
})
.catch((error) => {
console.log(error);
});
}
Someone can explain that ?
When you get TypeError: Network request failed, it means that, well, the network request failed. It could mean the API / server you're trying to connect to is down / not listening for connections anymore.
Regarding SyntaxError: Unexpected token < in JSON at position 0, that's what you get when trying to parse non-JSON as JSON. Typically here it's likely your API / server failing to fulfill your request and, instead of JSON, serving you an HTML error page.
You might want to check if data.ok is true before trying to parse the JSON response (data.json()).