Axios Interceptors with given token, React - reactjs

After this request:
axios
.post(url_auth, obj)
.then(response => {
const info = response.data
this.setState({info})
})
.catch(error => {
console.log(error);
});
I store inside info a JSON with id and token. (backend sent it to me)
I would like now to store token in the headers of every request I made.
How do I make it with? I guess with interceptor? Once I configure the headers inside the interceptor (I'm trying to understand how), how do I call it in my request?
Thank you very much!

Yes this can be done with the interceptors.Refer this article
Also you can refer one of my repo,The project is in Angular & Node.Used Token for validating the request

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 :/

HERE Geocoding API - not working inside my React app

I have a React app in which I use the HERE Geocoding API. I have an axios request to retrieve latitude and longitude and it does not work as well as expected. The request is not working inside my app
return axios.get(`https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=myAPIKey`)
I have a 401 error. Bearer token invalid. Bearer missing or bearer value missing. If I open a new tab in my browser and paste the url https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=myAPIKey it works fine and I get the result I need.
I tried using the Authorization header
const config = {
headers: {
'Accept': 'application/json',
'Authorization': `apiKey myAPIKey`,
}
};
return axios.get(`https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=myAPIKey`,config)
In the Authorization header, I tried with Bearer and Basic instead of apiKey
documentation HERE API
In the documentation about how to create an API Key and how to use it, the only thing I need to do is what I have already done. I have created a project, an API Key and I use it in my request.
HERE Geocoding API Key
I don't know how the HERE api works but the error message is probably the answer you are looking for.
You are likely to provide the api key via the Authorization header with your request. Read about the header on MDN
You just need to pass your API key in the link as a parameter.
Just sign up and you can get your API key.
https://developer.here.com/sign-up
The code should be like this.
return axios.get(`https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=${HERE_MAP_API_KEY}`,config)
The latest request would look like this.
axios.get(`https://geocoder.ls.hereapi.com/search/6.2/geocode.json?languages=en-US&maxresults=${maxResults}&searchtext=${query}&apiKey=${HERE_MAP_API_KEY}`)
.then(res => {
const data = res.data
console.log(data)
})
.catch(err => console.log(err))

how to solve 401 error in react native web?

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.

How to add custom HTTP headers in React application?

I have a react js application. I want to add some http headers in the every response that's being returned from the app. Could you please suggest how to implement this !
NOTE : I am not trying to call any api with headers in request. I want my react app to respond with some custom headers in the response
As Dovlet Mamenov mentioned in the comment, this has to be done on the web server wherever react app is hosted.
For example, If react app is hosted on the Apache server, then these http headers in the response should be added on the Apache server conf.
const header = new Headers();
header.append('Access-Control-Allow-Origin', '*');
const body = {
author: author,
text: text
}
axios.post("https://api.test/posts/create", body, header)
.then((res) => {
this.setState({
result: res
});
})
.catch((error) => {
this.setState({
error: error.message
});
})
You have to use the native object Headers, and add it in axios.

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