So I got everything to work in postman but I’m having trouble getting it to actually work on my web app.
indent preformatted text by 4 spaces
optimize=()=>{
let url = 'https://api.routexl.com/v2/tour/?'
// locations=[{"address":"The Hague,TheNetherlands","lat":"52.05429","lng":"4.248618"},{"address":"TheHague,TheNetherlands","lat":"52.076892","lng":"4.26975"},{"address":"Uden, TheNetherlands","lat":"51.669946","lng":"5.61852"},{"address":"Sint-Oedenrode, TheNetherlands","lat":"51.589548","lng":"5.432482"}]'
let username = 'user';
let password = 'pass';
let yeet = `[{"address":"The Hague,TheNetherlands","lat":"52.05429","lng":"4.248618"},{"address":"TheHague,TheNetherlands","lat":"52.076892","lng":"4.26975"},{"address":"Uden, TheNetherlands","lat":"51.669946","lng":"5.61852"},{"address":"Sint-Oedenrode, TheNetherlands","lat":"51.589548","lng":"5.432482"}]`
fetch(url, {method:'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Basic ' + btoa(username + ":" + password),
},
body: JSON.stringify(
{locations: yeet}
)
})
.then(response => response.json())
.then(json => console.log(json));
//.done();
// function parseJSON(response) {
// return response.json()
// }
}
We’ve no experience with React, but you only need to JSON the value of the locations
parameter, not the parameter itself. You may want to try something like:
body: { locations: JSON.stringify( yeet ) }
The problem was using JSON in the first place, the only way I could get it was pre-formatting the body for x-www-form-urlencoded.
I hope this helps someone out who ends up in my predicament!
this.postRoute(this.state.routeName)
let modifiedAddressList =[]
this.state.addressList.map((addressObj)=>{
let addressString = {"address":`${addressObj["address"]}`,"lat":`${addressObj["lat"]}`,"lng":`${addressObj["lng"]}`}
return modifiedAddressList.push(addressString)
})
///the code below handles formatting the code for the body
let yeet = JSON.stringify(modifiedAddressList)
let url = `https://api.routexl.com/v2/tour/?`
let username = 'pass';
let password = 'word';
let details = {
locations: yeet
}
/////this code handles the formatting for the formbody
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch(url, {method:'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
'Authorization': 'Basic ' + btoa(username + ":" + password),
},
body: formBody
})
.then(response => response.text())
.then(text => {
let textObj = JSON.parse(text)
let waypointData = textObj["route"]
let objArray = Object.keys(waypointData).map(i => waypointData[i])
this.setState({
optimizedRoute: objArray
})
1 Like