I am trying to use the Javascript fetch API to access the RouteXL Trip API.
I have the request working in Postman, it's very simple and it works:
Now I am trying to replicate that request using the Javascript fetch API but I just can't get it to work. The API is not seeing the 'locations' data. I've tried the same thing in a Node.js server using the Got library and am facing the same problem.
This is what my browser code looks like (I have tried MANY variations):
const url = `https://api.routexl.nl/tour`;
const locations = this.makeLocations(tasks,trip);
const params = {
  skipOptimisation: true,
  locations:locations
}
const request = new Request(url, {
  method: 'POST',
  headers: {
    'Authorization': 'Basic authToken',
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: JSON.stringify(params)
})
const response = await fetch(request)
console.info("Response:", response)
The locations data that is being returned from
this.makeLocations(tasks,trip);
is the same data that I have pasted into Postman.
Here is another attempt using FormData:
const form = new FormData();    
const locations = [
      { "address": "Start", "lng": -1.81, "postcode": "B33 8QE", "lat": 52.48, "servicetime": 0 }, 
      { "address": "24631000021902777", "lng": -2.440442, "postcode": "HR8 1PS", "lat": 52.088603, "servicetime": 22 }, 
      { "address": "End", "lng": -1.81, "postcode": "B33 8QE", "lat": 52.48, "servicetime": 0 }
    ]
    form.append("locations", JSON.stringify(locations));
    const request = new Request(url, {
      method: 'POST',
      headers: {
        'Authorization': 'Basic myToken'
      },
      body:form
    })
I have also tried using qs stringify on the locations but still get the same result.
Another attempt (same result) based on Post a x-www-form-urlencoded request from React Native:
const locations = JSON.stringify([
  { "address": "Start", "lng": -1.81, "postcode": "B33 8QE", "lat": 52.48, "servicetime": 0 }, 
  { "address": "24631000021902777", "lng": -2.440442, "postcode": "HR8 1PS", "lat": 52.088603, "servicetime": 22 }, 
  { "address": "End", "lng": -1.81, "postcode": "B33 8QE", "lat": 52.48, "servicetime": 0 }
])
let formBody = [];
formBody.push(encodeURIComponent("locations") + "=" + encodeURIComponent(locations));
formBody.push(encodeURIComponent("skipOptimisation") + "=" + encodeURIComponent(true));
const request = new Request(url, {
  method: 'POST',
  headers: {
    'Authorization': 'Basic myToken'
  },
  body:formBody.join("&")
})
const response = await fetch(request)

 
    