How can i get response from fetch API React Native - json

{
"success":true,
"result":{
"sessionName":"2a7777703f6f219d"
"userId":"19x1"
"version":"0.22"
}
};
fetch('https://myapi/api', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'xxxx1',
secondParam: 'xxxx1',
})
})
How can i get response from fetch API React Native (Post method)
I need to console.log to see sessionName in result (I think it's response.result.sessionName)
But I don't know how to get it from fetch.
Where is response from fetch like a get method
Here's Get method from facebook (it's have response)
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}

You can just do the same as GET method:
fetch('https://myapi/api', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'xxxx1',
secondParam: 'xxxx1',
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);// your JSON response is here
})
.catch((error) => {
console.log(error);
});

Related

Get TypeError Network Request Failed using react native fetch json url

I would like to create simple apps that make user can post data to json.
Here is my code.
componentDidMount = () => {
fetch('https://site.json',
{
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": 'application/json',
},
body: JSON.stringify({
value: 'React POST Request Example'
})
}
).then(response => response.json()).then(data => console.log(data))
.catch(err => console.log("api Erorr: ", err));
}
But finally, I get an error api Erorr: [TypeError: Network request failed]
Is it Cors block my access???
Any idea how to solve it, Thank you very much
There is something wrong with the URL. The same code working fine with other urls like.
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
value: 'React POST Request Example',
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((err) => console.log('api Erorr: ', err));
}}

How to convert json to a fetch function in react

the parameter with attribute named file is required and the actual curl command is:- curl -F "file=#password.txt" https://safenote.co/api/file -F password=secret -F lifetime=72 and the corresponding json format is:-
{
"url": "https://safenote.co/api/file",
"raw_url": "https://safenote.co/api/file",
"method": "post",
"files": {
"file": "password.txt"
},
"data": {
"password": "secret",
"lifetime": "72"
}
}
I need this to be converted into a fetch function or using axios, I'm not understanding which is the body part ad what to include
I have tried :-
fetch(`https://safenote.co/api/file`,{
mode:'no-cors',
method:"POST",
// headers: {
// "Content-Type": "application/json"
// },
"files":{
"file":selectedFile,
},
// body: JSON.stringify({
// file:selectedFile
})
// })
.then(response => response.json())
.then(data => console.log("data",data))
.catch(error => console.log(error));
}
my HTML part
<input type="file" name="attachment" accept="image/png, image/jpeg" onChange={(e) => setSelectedFile(e.target.files[0])}/>```
You can use axios and form data for that
const myFormData = new FormData();
myFormData.append('files', 'file');
You can add another properties like name or whatever too
myFormData.append('name', 'myFileName');
then use the axios
axios({
method: "post",
url: "myurl",
data: myFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});

React Axios Error in IE 11, but Not Chrome

The following works in Chrome, but gives Network Error in IE 11. Same with using Fetch instead of Axios.
What am I missing?
async componentDidMount() {
var auth = "Basic " + btoa(process.env.REACT_APP_CREDENTIAL);
var state = this;
Axios.get(
process.env.REACT_APP_URL,
{
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: auth,
},
withCredentials: true,
}
)
.then(function (response) {
console.log(response.status);
state.setState({ data: response.data.value });
})
.catch(function (error) {
console.log(error);
});
}

Fetching from API in React with key in headers, returning 406 not acceptable

I'm trying to fetch from an API, using an API key, but keep getting 406 Not Acceptable.
I can get the request to work in Postman, but not in the code. What could be wrong here? I've tried all sorts of ways of including my info in headers, this is just my last attempt.
componentDidMount() {
fetch("my-api", {
method: "GET",
headers: ({
Accept: "application/json",
"Content-Type": "application/json",
"X-Api-Version": 20161108,
Authorization: {
Token: "my-api-key",
}
}),
body: JSON.stringify()
}).then(response => {
if (response.status === 201) {
console.log(response)
return response.json()
} else {
console.log("oh no!", response.status === 404)
}
})
}
I figured it out. This ended up working:
componentDidMount() {
fetch("my api", {
method: "GET",
headers: ({
Accept: "application/vnd.api+json",
"Content-Type": "application/json",
"X-Api-Version": 20161108,
Authorization: "Token my token",
}),
body: JSON.stringify()
}).then(response => {
if (response.status === 200) {
console.log(response)
return response.json()
} else {
console.log("oh no!", response.status === 404)
}
})
}

Making a JSON Object as Google Maps API Call in React Native

I wanted to call GoogleMapsAPI and get results with specified origin and destination. However, I cannot pass the result of the api call immediately because it returns the result after I do assign operation. I wanted to pass the result immediately but I couldn't find any proper solution. Here is my fetch code for API.
class RouteSelection extends Component {
constructor(props) {
super(props);
this.fetchApi = this.fetchApi.bind(this);
this.fetchDef = this.fetchDef.bind(this);
this.fetchFewer = this.fetchFewer.bind(this);
this.fetchLess = this.fetchLess.bind(this);
this.fetchBestGuessTraffic = this.fetchBestGuessTraffic.bind(this);
this.fetchPessimisticTraffic = this.fetchPessimisticTraffic.bind(this);
this.fetchOptimisticTraffic = this.fetchOptimisticTraffic.bind(this);
this.calcRoutes = this.calcRoutes.bind(this);
this.state = {
origin: "",
destination: "",
arrival_time: "",
def_data: [],
f_data: [],
l_data: [],
best_guess: [],
pessimistic_guess: [],
optimistic_guess: [],
};
}
fetchDef(){
fetch("https://maps.googleapis.com/maps/api/directions/json?origin=" + this.state.origin + "&destination=" + this.state.destination +"&key= API_KEY&mode=transit&alternatives=true", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((responseData) => this.setState({ def_data: responseData.routes }))
.catch((error) => {
Alert.alert(
'Network Request Failed',
'Server cannot retrieve users from server. Please chech the internet connection',
[
{ text: 'OK' }
]
)
});
}
fetchLess(){
fetch("https://maps.googleapis.com/maps/api/directions/json?origin=" + this.state.origin + "&destination=" + this.state.destination +"&key= API_KEY&mode=transit&alternatives=true&transit_routing_preference=less_walking", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((responseData) => this.setState({ l_data: responseData.routes }))
.catch((error) => {
Alert.alert(
'Network Request Failed',
'Server cannot retrieve users from server. Please chech the internet connection',
[
{ text: 'OK' }
]
)
});
}
fetchFewer(){
fetch("https://maps.googleapis.com/maps/api/directions/json?origin=" + this.state.origin + "&destination=" + this.state.destination +"&key= API_KEY&mode=transit&alternatives=true&transit_routing_preference=fewer_transfers", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((responseData) => this.setState({ f_data: responseData.routes }))
.catch((error) => {
Alert.alert(
'Network Request Failed',
'Server cannot retrieve users from server. Please chech the internet connection',
[
{ text: 'OK' }
]
)
});
}
fetchBestGuessTraffic(){
fetch("https://maps.googleapis.com/maps/api/directions/json?origin=" + this.state.origin + "&destination=" + this.state.destination +"&key= API_KEY&mode=transit&alternatives=true&traffic_model=best_guess", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((responseData) => this.setState({ best_guess: responseData.routes }))
.catch((error) => {
Alert.alert(
'Network Request Failed',
'Server cannot retrieve users from server. Please chech the internet connection',
[
{ text: 'OK' }
]
)
});
}
fetchPessimisticTraffic(){
fetch("https://maps.googleapis.com/maps/api/directions/json?origin=" + this.state.origin + "&destination=" + this.state.destination +"&key= API_KEY&mode=transit&alternatives=true&traffic_model=pessimistic", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((responseData) => this.setState({ pessimistic_guess: responseData.routes }))
.catch((error) => {
Alert.alert(
'Network Request Failed',
'Server cannot retrieve users from server. Please chech the internet connection',
[
{ text: 'OK' }
]
)
});
}
fetchOptimisticTraffic(){
fetch("https://maps.googleapis.com/maps/api/directions/json?origin=" + this.state.origin + "&destination=" + this.state.destination +"&key= API_KEY&mode=transit&alternatives=true&traffic_model=optimistic", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((responseData) => this.setState({ optimistic_guess: responseData.routes }))
.catch((error) => {
Alert.alert(
'Network Request Failed',
'Server cannot retrieve users from server. Please chech the internet connection',
[
{ text: 'OK' }
]
)
});
}
fetchApi() {
this.fetchFewer();
this.fetchLess();
this.fetchDef();
this.fetchBestGuessTraffic();
this.fetchOptimisticTraffic();
this.fetchPessimisticTraffic();
}
calcRoutes(){
console.log("Fewer Transfers ");
console.log(this.state.f_data);
console.log("Less Walking ");
console.log(this.state.l_data);
console.log("Default ");
console.log(this.state.def_data);
console.log("Best Guess Traffic ");
console.log(this.state.best_guess);
console.log("Optimistic Guess Traffic ");
console.log(this.state.optimistic_guess);
console.log("Pessimistic Guess Traffic ");
console.log(this.state.pessimistic_guess);
this.props.navigator.push({
id: 'UserPref',
name: 'UserPref',
});
}
The above code implies that there are many asynchronous calls. In order to get defined values in logs you need to implement either async/await , callback or .then() i.e resolve promise.
we will implement callback in the above code snippet:-
I will do one for you and rest is for practice...
wherever you are calling onPress={() => this.fetchApi(function(data){calcRoutes(data)}) } just pass a callback..and instead of calling calcRoutes() function from different method call it here because you don't know when will response come.
After that :
fetchApi(callback) {
this.fetchFewer(function(data){callback(data)});
}
fetchFewer(callback){
fetch("https://maps.googleapis.com/maps/api/directions/json?origin=" + this.state.origin + "&destination=" + this.state.destination +"&key= API_KEY&mode=transit&alternatives=true&transit_routing_preference=fewer_transfers", {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((responseData) => {this.setState({ f_data: responseData.routes }) callback(responseData.routes)})
.catch((error) => {
Alert.alert(
'Network Request Failed',
'Server cannot retrieve users from server. Please chech the internet connection',
[
{ text: 'OK' }
]
)
});
}
This is how callback works...
Cheers :)