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!
Related
I am using axios to make apis calls in react. If there is no token provided or token got expired server sends the 401 status. I want to check that status on reactjs side.
But if i check err object in catch the status field is null.
Here is the code
try {
MyService.getIntet(reqBody);
} catch (err) {
handleUnAuthorizedResponse(err);
}
error returns this
Service function:
import axios from "axios";
static getIntent(reqBody) {
const url = `${this.intentionBaseUrl}/process`;
const options = {
headers: {
"Content-Type": "application/json"
},
};
return axios
.post(url, reqBody, options)
.then((res) => res.data)
}
How to handle 401 error ?
You need to wrap the trycatch in async function and await MyService.getIntet(reqBody) to catch the error. The status code is in err.response.status.
You could also just MyService.getIntet(reqBody).catch(handleUnAuthorizedResponse) if you don't want to wrap it in async function.
You can use .catch chaining function after .then to catch all errors.
Error object will contain a response object which will contain actual response received by API response with all meta information. But make sure to put a condition while accessing this object as errors caught from the then block will not have response key.
import axios from "axios";
static getIntent(reqBody) {
const url = `${this.intentionBaseUrl}/process`;
const options = {
headers: {
"Content-Type": "application/json"
},
};
return axios
.post(url, reqBody, options)
.then((res) => res.data)
.catch(error => console.log(error.response.status))
}
I am trying to use Camunda's REST api to deploy a new process. However, I keep getting this HTTP response when my function is called.
Response:
{"type":"InvalidRequestException","message":"No deployment resources contained in the form upload."}
My jsx function
async deployNewProcess(xmlData) {
const formData = new FormData()
const blob = new Blob([xmlData], {type:'application/octet-stream'})
formData.append('upload', blob)
const response = await fetch(`${baseurl}/deployment/create`, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data; boundary=<calculated when request is sent>',
'Content-Length': '<calculated when request is sent>',
'Host': '<calculated when request is sent>'
},
body: formData
})
.then(result => console.log("SUCCESS: ", result))
.catch(err => console.log("ERROR: ", err))
}
Has anyone had any experience with this?
Based on this post https://camunda.com/blog/2018/02/custom-tasklist-examples/
see the example code
here:
https://github.com/camunda-consulting/code/blob/b2c6c3892d3d8130c0951a1d3584be7969fec82a/snippets/camunda-tasklist-examples/camunda-react-app/src/middleware/api.js#L11
and here:
https://github.com/camunda-consulting/code/blob/b2c6c3892d3d8130c0951a1d3584be7969fec82a/snippets/camunda-tasklist-examples/camunda-react-app/src/actions/camunda-rest/deployment.js#L4
I'm getting my token from an API but unfortunately my API is returning 400 bad request. I've already checked my api via Postman and it's working fine there. Kindly let me know solution or any mistake.
async componentWillMount(){
axios.post('http://api.myapiurl.com/token', {
grant_type: 'PASSWORD',
username: 'MY_USERNAME',
password: 'MY_PASSWORD'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then(response => {
console.log(response.data)
}).catch(err => console.log("api Erorr: ", err.message))
}
error in response below
Request failed with status code 400
- node_modules\axios\lib\core\createError.js:16:24 in createError
- node_modules\axios\lib\core\settle.js:18:6 in settle
- ... 10 more stack frames from framework internals
It is Solved by using QueryString.stringify(). I just pass the body into QueryString.stringify() like below:
axios.post('http://api.apiurl.com/token', QueryString.stringify({
grant_type: 'MY_GRANT_TYPE',
username: 'MY_USERNAME',
password: 'MY_PASSWORD'
}), {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
}).then(response => {
console.log(response.data)
}).catch(err => console.log("api Erorr: ", err.response))
From what I can see you are sending json data, but your Content-Type header is set to application/x-www-form-urlencoded; charset=UTF-8. if your api is expecting json then it should be application/json.
try using fetch instead, might be some axios bug, you dont need to add any libraries, here is an example:
fetch("http://api.myapiurl.com/token", {
method: "POST", // *GET, POST, PUT, DELETE, etc.
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
grant_type: "PASSWORD",
username: "MY_USERNAME",
password: "MY_PASSWORD"
})
})
.then(res => {
res.json();
})
.then(data => console.log(data)) // ur data is here
.catch(err => console.log("api Erorr: ", err));
First install the package axios from the url https://www.npmjs.com/package/react-native-axios
Then create two service for handling get and post request so that you can reuse them
GetService.js
import axios from 'axios';
let constant = {
baseurl:'https://www.sampleurl.com/'
};
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
}
};
export const GetService = (data,Path,jwtKey) => {
if(jwtKey != ''){
axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
}
try{
return axios.get(
constant.baseUrl+'api/'+Path,
data,
config
);
}catch(error){
console.warn(error);
}
}
PostService.js
import axios from 'axios';
let constant = {
baseurl:'https://www.sampleurl.com/'
};
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
}
};
export const PostService = (data,Path,jwtKey) => {
if(jwtKey != ''){
axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
}
try{
return axios.post(
constant.baseUrl+'api/'+Path,
data,
config
);
}catch(error){
console.warn(error);
}
}
Sample code for using get and post services is given below
import { PostService } from './PostService';
import { GetService } from './GetService';
let uploadData = new FormData();
uploadData.append('key1', this.state.value1);
uploadData.append('key2', this.state.value2);
//uploadData.append('uploads', { type: data.mime, uri: data.path, name: "samples" });
let jwtKey = ''; // Authentication key can be added here
PostService(uploadData, 'postUser.php', jwtKey).then((resp) => {
this.setState({ uploading: false });
// resp.data will contain json data from server
}).catch(err => {
// handle error here
});
GetService({}, 'getUser.php?uid='+uid, jwtKey).then((resp) => {
// resp.data will contain json data from server
}).catch(err => {
// handle error here
});
Reference from one of my another post Post action API with object parameter within the URL
If you have any doubts, feel free to know
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.
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);
});