I'm trying to call the mapbox api to get navigation instructions.
Here's the doc: https://docs.mapbox.com/api/navigation/#using-http-post
And here's my api call:
fetch(`https://api.mapbox.com/directions/v5/mapbox/walking?access_token=${Config.MAPBOX_API_KEY}`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({
coordinates: "2.344003,48.85805;2.34675,48.85727;",
}),
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
Unfortunately I get a 422 unprocessable entity error:
I have tried differente coordinates as well...do you guys know what am I missing?
You're passing your coordinates in as a string, but the API expects a number, which is why you're getting a 422. Try this:
fetch(`https://api.mapbox.com/directions/v5/mapbox/walking?access_token=pk.eyJ1IjoiYmRkYXZpZHNvbiIsImEiOiJjaW41MWU5bTcwY2k1dXdtNG54cnhlczFsIn0._R6SrAak5_qF8l31JvSBIA`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'coordinates=2.344003,48.85805;2.34675,48.85727', // <--- Body changed to pass numbers instead of strings
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
Related
I have a handleSubmit function that I have added two post requests to.
However, one of the post requests relies on the data returned from the first post request. I've attempted to access this data by setting it to a var but it doesn't seem accessible within the second fetch. Not sure if my syntax is wrong.. any ideas?
I believe this should be working but I'm not sure where I'm going wrong. Thanks!
handleSubmit = () => {
fetch('http://localhost:3000/resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
name: this.state.name,
description: this.state.description,
link: this.state.link,
topic_id: this.state.topic_id
})
})
.then(res => res.json())
.then(data => {
this.props.addResource(data)
var dataId = data.id;
})
return fetch('http://localhost:3000/user_resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
resource_id: dataId,
user_id: this.props.users.id
})
})
.then(res => res.json())
.then(data => {
this.props.addUserResource(data)
})
this.props.navigation.goBack()
}
There's 2 problems:
You return some code and then try to run something else. Your this.props.navigation.goBack() statement will never be reached because the function ends when it reaches the return. That is not your main problem though.
fetch is asynchronous. It means that the function handleSubmit will read the two first statements ("fetch resources" and "return fetch user_resources") and then when each fetch is finished they will run their .then() functions.
This means your dataId will be undefined and you need to wait for the first fetch to complete and to execute the 2nd fetch.
handleSubmit = () => {
fetch('http://localhost:3000/resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
name: this.state.name,
description: this.state.description,
link: this.state.link,
topic_id: this.state.topic_id
})
})
.then(res => res.json())
.then(data => {
this.props.addResource(data)
return fetch('http://localhost:3000/user_resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
resource_id: data.id,
user_id: this.props.users.id
})
})
})
.then(res => res.json())
.then(data => {
this.props.addUserResource(data)
})
this.props.navigation.goBack()
}
I have been trying to make a post request to send formData using axios / fetch, but every time i make a request it throws "Network Error". I have been trying this for couple of days but couldn't do it.
var file = new File([this.state.selectedFileObj], "ISDD_" + this.state.fileName, { lastModified: new Date().getMilliseconds() })
formdata.append("file", file, this.state.fileName);
formdata.append("folderName", this.state.folderName);
formdata.append("userName", "user#domain.com");
formdata.append("documents", documents);
// 1st approach
RNFetchBlob.fetch('POST', url, {
"Content-Type": 'multipart/form-data',
"enctype": 'multipart/form-data',
"Cache-Control": 'sno-cache',
"Pragma": 'no-cache'
}, formdata)
.then((response) => console.log(`1 ${response.text()}`))
.then((RetrivedData) => {
console.log(`2 ${RetrivedData}`);
})
.catch((err) => {
console.log(`err ${err}`);
})
//2nd approach
axios({
url: url, formdata,
method: 'POST',
headers: {
"Content-Type": 'multipart/form-data',
'enctype': 'multipart/form-data',
'Cache-Control': 'sno-cache',
'Pragma': 'no-cache'
},
data: formdata
})
.then((response) => {
console.log(`1 ${response}`)
})
.catch((error) => {
console.log(error)
})
Need a solution for it,
Thanks,
I use fetch to send data to webservice. How can I do this with axios ?
fetch('url', {
method: 'POST',
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json', // <-- Specifying the Content-Type
}),
body: JSON.stringify(object)
})
Here is some code that is close to what you want.
axios({
method: 'post',
url: 'myurl',
data: bodyFormData,
config: { headers: {'Content-Type': 'application/json' }}
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
Alternately, you can set you configuration then use axois.post(). This axios cheatsheat may help you as well.
There's a fetch post with "userid" as a parameter. I've tested the url and parameter in native android, it works there but here it doesn't take the parameter. It always sends the null value to "userid" parameter. Am I doing smthing wrong here?
fetch('http://zzz.com/zzz/api/battery/gpswithbattery', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
userid: '404',
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
//return responseJson.message;
this.setState({
data: responseJson.message
})
})
.catch((error) => {
console.error(error);
});
I see no mistake you are doing here, and start using es7 syntax, as that'll be even cleaner and easy to find mistakes,
pro-tip: use prettier that'll make to look your code better.
const method = async () => {
const reponse = await fetch("http://zzz.com/zzz/api/battery/gpswithbattery", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
userid: "404"
})
});
const responseJson = await response.json();
this.setState({ data: responseJson.message });
};
Im trying to handle a "Network request failed" error (I already allowed unsecured connections from Xcode), But when i try to do something inside the .error() function it crashes and says: .error is not a function; The fetch() works already.
here's an example of it, Im trying to run this code after a fetch function.
fetch('URL',{
'method': 'POST',
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
'body': data}
)
.then((response) => response.json())
.then((responseJson) => {
//Do something
})
.error((error)=>{
console.error(error);
Actions.login()
});
React's fetch method returns a Promise, which doesnot have .error() method. Instead it has .catch() method to catch all errors when fetch fails.
fetch('URL', {
'method': 'POST',
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
'body': data
})
.then((response) => response.json())
.then((responseJson) => {
//Do something
})
.catch((error) => {
console.error(error);
Actions.login()
});