我正在尝试使用Javascript提取API访问RouteXL Trip API。
我有在邮递员中处理的请求,它很简单,并且有效:
现在,我正在尝试使用Javascript提取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(tasks,trip);
与我粘贴到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
字符串化,但仍得到相同的结果。
基于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)
答案 0 :(得分:0)
我从来没有碰上raw
和FormData
一起使用x-www-form-urlencoded
库的情况。
您的代码如下所示。
qs
希望这会有所帮助。