how to solve 401 error in react native web? - reactjs

I am trying to make an axios get request but am receiving 401 everytime am trying to fetch. However am already logged in as I have previously received my user login response
My project has been built with react native init and is running on browser using react-native-web.
The same api when I check the response on mobile and postman it is giving the correct response however on browser it is throwing 401
below is my axios code
useEffect(() => {
let url = `${ROOT}/children/${id}/vaccinations`;
axios
.get(url)
.then(function (res) {
console.log("Hello", res);
setData(res.data.content);
})
.catch(function (err) {
console.log(err);
});
}, []);
The response of 3 apis that are being called
The error that am receiving
[![enter image description here][2]][2]
could anyone please tell me where am going wrong?
any help would be appreciated.
[2]: https://i.stack.imgur.com/17Qyf.png

401 code error means you are not authorized, you would need to send your user token that you receive from the backend as a header when sending your specified request, something like that:
axios.get('https://api.github.com/user', {
headers: {
'Authorization': ${access_token}
}
})
You can read more about sending tokens in headers via this link:
https://flaviocopes.com/axios-send-authorization-header/
I hope this helps in solving your issue.

Related

Post Request from axios always returns Unauthorized despite having valid JWT set in header/Axios Deletes Headers

I set up passport-local to login a user, and then once logged in, the user will be given a JWT token through passport-JWT. The JWTStrategy is set up to use
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken() so that the JWT can sent with the Authorization header Authorization: `Token ${userContext.token}`}. In my react client side, I have set up a GET request using axios as shown here:
const fetchProfileDetails = async(config)=>{
const res = await axios.get("http://localhost:8080/users/me", config)
}
const config = {
method:"GET",
withCredentials: true,
headers: {Authorization: `Bearer ${userContext.token}`}
}
This request successfully authenticates and returns the user data from /me.
Now heres the kicker: when I use the exact same request structure, but switch the method to post in the axios request and in my express route in the backend, the request always responds with a 401 Unauthorized.
However, when I send the same request from POSTMAN, with the same Bearer Token used in the request that was Unauthorized, the request succeeds without any errors.
TLDR: GET requests work with the JWT token and return with a 200 status code, while the same request with a POST method returns with a 401 status code.
What am I missing here??!
You are probably using there GET and not using POST anywhere.
In your code, you have code only for get. You will need to write code for post as well.
Below is the code for post for your reference:
router.post('/', config, async(req, res, next) => {
const { error } = validateBody(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
}
const newData= new passport({ name: req.body.name });
await newData.save();
console.log('saving the document');
res.send(newData);
})
Your code should have post as well. Writing single code will not work. You need to have to write code for every condition and every possibility. So like for get need code for post as well, also if you have condition for patch or delete or put you will have to write the axios method for that as well.
Hope this has helped you in any way.
I have come upon a solution for this issue. For some reason, axios was not maintaining the Authorization header I had set in my config variable, and deleted it upon making the request. To solve this, I just had to reshuffle my axios request to look like this:
const res = await axios({
method:'POST',
url:"http://localhost:8080/users/test",
headers:{'Authorization':`Bearer${token}`
}})
I feel cheated as I spent a ton of time on this and the solution was so underwhelming. Axios was trolling me the whole time :/

Failed to load resource: the server responded with a status of 401 in axios call and Cookies has been rejected because a non HTTP key can't be secure"

I am trying to fetch some data using axios GET request
How do i resolve it? This works on someone else's computer but it does'nt work on mine. The api docs, urls api config everything is alright. It just does'nt work on my computer. I have tried different browsers too others facing the same problem switched the browser from chrome to firefox and it worked but it does'nt in my case.
It shows 401 and "Cookies has been rejected because a non HTTP key can't be secure"
const [courseId, setCourseId]
const getAllcourse = () => {
axios
.get(`${appConfig.host}${urls.getSpecificCourse}?courseId=${courseId}`)
.then((success) => {
console.log("Get all courses", success.data);
})
.catch((error) => {
console.log(error);
});
};

TypeError: Failed to fetch in Reactjs

I am using fetch to post data on backend. Every time, it is success but sometimes it caught error
The data was posted but still error is shown.
I am fetching by code : -
Compose.js
fetch(`${props.url}/addBalance`, {
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
body: JSON.stringify(obj)
})
.then(resp => resp.json())
.then(res =>{
if(res) alert('Added Successfully');
else alert('Failed,Try Again');
}).catch(err=> {console.log(err);alert(err)});
}
The CORS is enabled in backend and working (checked by POSTMAN).
Success:- Success
Caught Error :- without ACAO with ACAO
I run the fetch command in console and it worked fine but not in my React js App
Catch is logging error but still data is being posting
Error:- TypeError: Failed to fetch
If it was working fine on the server then the problem could be with the response headers. Check the Access-Control-Allow-Origin (ACAO) in the response headers. Usually react's fetch API will throw fail to fetch even after receiving response when the response headers' ACAO and the origin of request won't match.
Add Allow CORS: Access-Control-Allow-Origin extension to your chrome or browser then enable it and check the reponse after that
I was using Form to take the input from user due to which before fetching, page was reloaded and it showed 'failed to Fetch' and status was shown "Cancelled" in Chrome developer tools.
To fix this I used Div tag.

How to GET to LinkedIn API?

I am trying to retrieve user info from LinkedIn API, calling api.linkedin.com/me and sending token within axios. But I am getting 404 error - https://gyazo.com/b08b3eba1cbfd5809ede994b1af67fb5
I am able to get an access token from their API, but I stuck on getting user info
Here is a piece after I get a token I call api.linkedin.com/me like:
.then(function (response) {
axios.get('https://api.linkedin.com/me', {
headers: {
Authorization: 'Bearer ' + response.data.access_token
}
}).then(function (response) {
console.log(response)
})
})
.catch(error => {console.log(error)})
}
I need to be able to fetch data of the user, but I cannot make a valid request
Thank you in advance!
Changing the get URL to https://api.linkedin.com/v2/me should solve the problem.
I say this because https://api.linkedin.com/me redirects to a 404 page on linkedin, however, https://api.linkedin.com/v2/me returns a json response.

React+axios api call returning 401 error, postman is able to get access

first time posting.
I am building a simple react app to display a list from an api that has basic auth. I am able to use postman and curl to successfully access the api and display the info. However when I try and call it in my code, I get a 401 error from the browser. I've tried a few variation of the code below and think that this is the closest to working. Many thanks in advance to any that can help or point me in the right direction. Also I have cors disabled as this just a frontend.
componentDidMount() {
const tok = 'KEY:password';
axios.get('https://api/*********/assets',
{headers : { 'Authorization' : 'Basic ' + tok }})
.then(function(response) {
console.log(response.data);
console.log(response.headers['Authorization']);
}).catch(err => console.log(err));
}

Resources