How to set Axios headers to a instance (not globally) - reactjs

I'm trying to send a get request to Google Books Api with axios.
It works if the Authorization headers is not set.
However after I log in to my app and set the Authorization headers to a token, Google Api responds with.
errors:[{domain: "global", reason: "authError", message: "Invalid Credentials", locationType: "header",…}]
message:"Invalid Credentials"
Sorry I'm still quite new to programming and I'd just like to know the best way to bypass that error. I tried setting the Authorization header to it's own instance instead of setting it globally but could not find a way to do that in the action call in my React app.
Please help and thanks in advance!

You can try like this
//Set the header
var header = {
'Content-Type': 'application/json',
'Authorization':'Bearer '.concat(USER_TOKEN)
}
axios.get(URL, header)
.then(response => {
console.log(JSON.stringify(response));
})
.catch((error) => {
console.log('error ' + error);
});

Thank you guys for your help! They didn't work for me because of the way I set up my jwt on the client side.
The code below ended up working for me because I just needed to override the global Authorization header.
import axios from 'axios';
const axiosInstance = axios.create({
baseURL: url
});
axiosInstance.defaults.headers.common = '';
export default axiosInstance;

To set the authorization token in headers using axios in get request you can try the following code:
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } }).then(response => {
console.log(response.data);
})
.catch((error) => {
console.log('error: ' + error);
});

Related

How to fetch customers in reactjs using shopify api

I am new to API. I want to fetch customers in reactjs using shopify customer api.
I'm using following code:
const apiUrl = `https://${process.env.GATSBY_SHOPIFY_API_KEY}:${process.env.GATSBY_SHOPIFY_PASSWORD}#${shopify-store}/admin/api/${version}/customers.json`;
useEffect(() => {
fetch(apiUrl , {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*'
},
mode: 'cors',
})
.then((response) => {
console.log('response:', response);
})
.catch((error) => {
console.error('Error:', error);
});
},[])
Above code is producing error:
Url with cedentials can not be used in FETCH
I also tried using AXIOS. Code is following:
const getData = async () => {
try {
const res = await axios.get(apiUrl);
console.log("res >>>", res)
} catch(error) {
console.log("error >>", error)
}
}
Above code is also producing error:
Access to XMLHttpRequest at 'apiUrl' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Please help me out with api!
Thanks in advance
I want to solve the issue as soon as possible. I have tried all the methods I could find on internet.

Cant post with axios network error reaxt native to heroku

I made a flask backend and deploy to heroku. It is working when i made a get request and made a post with postman json data. But i cant post when i use axios or fetch in react-native app.
const url = 'https://test.herokuapp.com/list/add';
const config = {
headers: { 'content-type': 'application/json' },
data: {
"test":this.state.testdata
},
};
const response = await axios.post(url, config)
.then(function(res){
console.log(res)
})
.catch(function(error) {
console.log('What happened? ' + error);
}); ```

How to fix the unauthorized axios/react response

Unauthorized axios/react response
Hi there friends, I'm trying to connect to an api through Axios and React but an error message appears saying that I don't have access here's my action:
import {SHOW_PROMOTIONS} from './action-types';
import axios from 'axios';
export const showPromo = () => async dispatch =>{
const url= 'https://payment-promotions-dev.travelit.com.ar/api/promotions/packages/';
let config = {
"Content-type": "application/x-www-form-urlencoded",
"Authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtdW5kaWdlYSIsImp0aSI6ImQ0ODE1ZDk4LTJlYmQtNDRjYS04NGViLTU4N2JjNTY5NzgzZCIsImlhdCI6MTU1NTM0ODUwMCwibm9tYnJlIjoiTXVuZGlnZWEiLCJhcHBsaWNhdGlvbklkIjoiMSIsInBhaXNJZCI6IjEiLCJ0aXBvQXBsaWNhY2lvbklkIjoiMSIsImFjdGl2YSI6IlRydWUiLCJuYmYiOjE1NTUzNDg1MDAsImV4cCI6MTU1NTk1MzMwMCwiaXNzIjoiVHJhdmVsSVQiLCJhdWQiOiJUcmF2ZWxJVCJ9.o4Tv6Cw1Mj5xmHIQQ7abm6k6Ean6s6eQ3IDEkHY6Frk"
};
axios.get('http://<host>:<port>/<path>', url,config)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
const respuesta = await axios.get(url,config);
dispatch({
type: SHOW_PROMOTIONS,
payload: respuesta.data
})
}
When I execute the component, this error appears: (See following image https://imgur.com/LuKnBv9)
The token is at it's respective header, I don't seem to recognize wat I'm doing wrong.
I even tried to do the request with Postman and it throughs 200: (See image2 https://imgur.com/7UFksPR)
Thanks for the help guys!
You currently aren't actually specifying headers for the request. You would need to add headers property to the config object and put the desired headers into that property. Also, as the comments have you stated, you would also need to specify the type for the Authorization request headers, such as Bearer:
const config = {
headers: {
"Content-type": "application/x-www-form-urlencoded",
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtdW5kaWdlYSIsImp0aSI6ImQ0ODE1ZDk4LTJlYmQtNDRjYS04NGViLTU4N2JjNTY5NzgzZCIsImlhdCI6MTU1NTM0ODUwMCwibm9tYnJlIjoiTXVuZGlnZWEiLCJhcHBsaWNhdGlvbklkIjoiMSIsInBhaXNJZCI6IjEiLCJ0aXBvQXBsaWNhY2lvbklkIjoiMSIsImFjdGl2YSI6IlRydWUiLCJuYmYiOjE1NTUzNDg1MDAsImV4cCI6MTU1NTk1MzMwMCwiaXNzIjoiVHJhdmVsSVQiLCJhdWQiOiJUcmF2ZWxJVCJ9.o4Tv6Cw1Mj5xmHIQQ7abm6k6Ean6s6eQ3IDEkHY6Frk"
}
};
Hopefully that helps!

axios doesn't send post data to the back-end

I'm new to react and.my problem is that i'm going to make a post request to my node back-end. using react-redux and axios. the thing is my back-end doesn't even hit the request. and no action on the network tab in the browser ether
I have tried lots of another answers but doesn't work
this code is in my redux action page
export const postNominationPayments = function
postNominationPayments(candidatePayments) {
let nominationPayments = {
depositor:candidatePayments.depositor,
depositAmount:candidatePayments.depositAmount,
depositeDate:candidatePayments.depositeDate,
filePath:candidatePayments.filePath,
status:candidatePayments.status,
nominationId:candidatePayments.nominationId
};
return function (dispatch) {
console.log("**",nominationPayments);
var headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
axios
.post(
`${API_BASE_URL}/nominations/payments`,
{
nominationPayments
},{headers: headers}
)
.then(response => {
console.log("))))))))))))",response);
// dispatch({
// type: POST_NOMINATION_PAYMENTS,
// payload: response.data
// })
})
.catch(error => {
console.log("===",error);
// dispatch({ type: AUTH_FAILED });
// dispatch({ type: ERROR, payload: error.data.error.message });
});
};
}
post data is coming as expected.also the back works correctly using postman. but it's not working.
couldn't think of a solution.
what is wrong with my code?
thanks in advance
It should be
axios.post(
`${API_BASE_URL}/nominations/payments`, nominationPayments,
{headers: headers}).
One can drop headers section as well a default is application/json
The way you are passing data to axios post request is incorrect. You need to pass something like below
Change
axios(
`${API_BASE_URL}/nominations/payments`,
{
nominationPayments
},{headers: headers}
)
To
axios.post(
`${API_BASE_URL}/nominations/payments`,
nominationPayments,
{
headers: headers
}
)
axios.get and axios.post takes different kind of arguments and could be hard to remember.
So I usually just stick to the more verbose way:
axios({
method: 'post',
url: `${API_BASE_URL}/nominations/payments`,
data: {
nominationPayments
},
headers
})
.then(response => {
// ...
})
.catch(error => {
// ...
})
Have you checked whether your MongoDB server is up and running?
In my case, my React server was running, however, my MongoDB servers were not. I ran both simultaneously and was able to post data to the back end.

"Error on Authentication Error: Network Error" in React authentication API call

I have made a authenticated API call..below my code is there i am getting "Error on Authentication Error"
componentDidMount()
{
let config = {'Authorization': 'Here i have pasted the auth key from Post mAN'};
axios.get('http://XX.XX.XX.XX/aa/bb/cc/list', { headers: config })
.then(function(response) {
console.log('Authenticated');
})
.catch(function(error) {
console.log('Error on Authentication' + error);
})
}
You may have send Authorization with Bearer. Do this way.
let config = {'Authorization': 'Bearer '+ key};
It depends on the type of authorization. If token authorization use
let config = {'Authorization': `Token ${key}`};

Resources