我正在尝试使用 Javascript 获取 API 来访问 RouteXL Trip API。
我有在 Postman 中工作的请求,它非常简单并且有效:
现在我正在尝试使用 Javascript fetch API 复制该请求,但我无法让它工作。API 没有看到“位置”数据。我已经在使用 Got 库的 Node.js 服务器中尝试了同样的事情,并且面临同样的问题。
这就是我的浏览器代码的样子(我尝试了很多变体):
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)
返回的位置数据
this.makeLocations(任务,旅行);
是我粘贴到 Postman 中的相同数据。
这是使用 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
})
我也尝试qs
在这些位置上使用 stringify,但仍然得到相同的结果。
基于Post a x-www-form-urlencoded 来自 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)