I am making an app where I send and receive data from one API. Once I get this data I want to make another call to the some other API sending this data to this second API and receiving data from this second API.
export const uploadImage = (data) => (dispatch) => {
dispatch({ type: UPLOAD_IMAGE });
axios({
method: 'post',
url: 'http://3.14.136.182:80/predict',
data: data,
"mimeType": "multipart/form-data",
headers: {
'content-type': 'multipart/form-data'
},
timeout: 20000
})
.then((response) => {
dispatch({ type: UPLOAD_IMAGE_SUCCESS, payload: response.data });
data = response.data;
axios({
method: 'post',
url: '3.14.136.182:8005/finalResult',
data: data,
"mimeType": "multipart/form-data",
headers: {
'content-type': 'multipart/form-data'
},
timeout: 20000
})
.then((response) => {
dispatch({ type: UPLOAD_IMAGE_SUCCESS, payload: response.data});
console.log("Mehmood",response.data);
})
.catch((error) => {
dispatch({ type: UPLOAD_IMAGE_FAILURE });
})
})
.catch((error) => {
dispatch({ type: UPLOAD_IMAGE_FAILURE });
})
}
You are missing at one return statement in you first then block. (before axios). Also you are dispatching success two times.
Related
This runs okay and request sent to the server successfully
axios({
method: "post",
url: `http://192.168.1.12:8000/user/image`,
data: {formData}
})
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
But this gives axios network error:
axios({
method: "post",
url: `http://192.168.1.12:8000/user/image`,
data: formData
})
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
I am using it the same way in my other project(react) but that works fine, here in this project(react-native) it gives axios network error if I don't enclosed the formData in {}.
Here is react frontend:
Here is react backend, as you can see I am getting the req.file and req.body does not have the formData:
Here is react-native result, formData is coming in req.body and req.file is undefined:
pass the headers likewise -
axios({
method: "post",
url: `http://192.168.1.12:8000/user/image`,
data: formData,
headers: { "Content-Type": "multipart/form-data" },
})
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
I am new to front-end. I use react and redux-form after I subbmit form on backend don't know how to handle response and present it with react. My response is simply only one number.
return function (dispatch, getState) {
dispatch({
type: CHANGE_ID_SUBMIT_DATA,
});
let reqBody = {
firstname: changeId.firstName
username: cnahgeId.userName,
};
return fetch(`${__REST_HOST__}/test/api/change/id`, {
credentials: 'include',
method: 'post',
headers: {
'Accept': 'application/json;charset=UTF-8',
'Content-Type': 'application/json;charset=UTF-8',
},
body: JSON.stringify(reqBody),
}).then(
response => dispatch(receiveData(response)),
error => dispatch({
type: CHANGE_ID_RESPONSE_ERR_DATA,
error
})
);
};
}
function receiveData(resp) {
console.log(resp.text());
return resp.text().then(response => dispatch({
type: CHANGE_ID_RESPONSE_DATA,
newId: response,
receivedAt: moment(Date.now())
}));
}```
In my project the API requires some data to be passed that is :
Bearer Token
Body - {email: [email_address]} e.g. {email: “mayank#gmail.com”}
Params - Your name i.e https://1234.amazonaws.com/alphabet/mayank
I am doing this in reactjs.
But I am confused how to use params.
My try:
method: 'POST',
headers: {
'Authorization': 'Bearer abcd',
},
body: JSON.stringify({
email: 'mayank#gmail.com'
})
};
fetch('https://1234.amazonaws.com/alphabet/mayank')
.then(res => res.json())
.then((data) => {
this.setState({
data: data,
});
},
But this is not working.
You should provide your parameters to the fetch request in an object like this. Read more about how to make post requests here.
fetch('https://1234.amazonaws.com/alphabet/mayank',
{
method: 'POST',
headers: {
'Authorization': 'Bearer abcd',
},
body: JSON.stringify({
email: 'mayank#gmail.com'
})
})
.then(res => res.json())
.then((data) => {
this.setState({
data: data,
});
},
I am wondering how I can sync my fetch method. I want to prevent rendering data in a component before a response is returned.
Here is my redux action with my fetch method:
export const FETCH_DATA_START = 'FETCH_DATA_START'
export const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS'
export const FETCH_DATA_FAILED = 'FETCH_DATA_FAILED'
export const getData = () => {
return (dispatch) => {
dispatch({
type: FETCH_DATA_START
})
fetch(baseUrl, {
credentials: "include",
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then((res) => {
dispatch({
type: FETCH_DATA_SUCCESS,
payload: res
})
})
.catch((err) => {
console.log(err)
dispatch({
type: FETCH_DATA_FAILED,
payload: 'error'
})
})
}
}
A common practice in this case is to set a flag like isFetching to true, and then display a loading spinner in your JSX based on the status of this flag.
Then when you received data, you hide this spinner and show the data.
So I have to update some user info ,it works fine on postman but when I try to type it in react-native I must be doing something wrong in the body of the fetch method. In postman I set x-www-form-urlencoded and type the keys like this :
Key ----- Value
moto ----- test
and that seems to work,but when I try to do the same on my code I somehow fail at it,here is my code
updateUser(){
return fetch(url,{
method: "PATCH",
headers: {
"X-Auth-Token": bearerToken,
"Content-Type":"application/x-www-form-urlencoded"
},
body: JSON.stringify({
moto: this.state.moto
}
})
}
)
I get 200 response which means the call works but I must be seting the parameter moto wrong somehow.
Any ideas ?
"Content-Type":"application/x-www-form-urlencoded"
should be
"Content-Type":"application/json"
form-urlencoded is way different from your body: JSON.stringify().
You'll want to use a FormData object instead:
const body = new FormData();
body.append('moto', this.state.moto);
fetch(url, {
method: "PATCH",
headers: {
"X-Auth-Token": bearerToken,
"Content-Type": "application/x-www-form-urlencoded"
},
body,
})
APICall = () => {
fetch(‘Your http URL’, {
method: 'PATCH',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
‘X-Auth-Token’: bearerToken,
},
body: JSON.stringify({
moto: this.state.moto
})
}).then((response) => response.json())
.then((responseJson) => {
if(responseJson.statuscode == 1) {
Alert.alert('Success');
} else {
Alert.alert(responseJson.message);
}
}).catch((error) => {
console.error(error);
});
}
finally fixed it by seting body to
body:
`moto=${this.state.moto}`
it appears that urlencoded headers require parameters in the form of
parameter1=value1¶meter2=value2
componentDidMount() {
return fetch(“Your URL”, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"Authorization": “token”
},
body: "firstName=Nikhil&favColor=blue&password=easytoguess"
})
.then((response) => response.json())
.then(function (data) {
alert(“Success”)
console.log('Request succeeded with JSON response', data);
})
.catch(function (error) {
alert("error occur")
console.log('Request failed', error);
});
}
const formData = new FormData();
formData.append('email', 'test#gmail.com');
formData.append('password', '123456');
fetch("https://test.com/api/login", {
method: 'post',
body: formData
})
.then(res => res.json())
.then(
(result) => {
console.log(result);
}).catch(err => {
console.log(err);
})