我试图将来自 fetch() 函数的请求从 js 应用程序发送到我的 Delhivery API,其格式如下所示:-
curl --request POST \ --url "https://track.delhivery.com/api/cmu/create.json" \ --header "Content-Type:application/json"\ --header "Accept:application/json"\ --header "Authorization: Token XXXXXXXXXXXXXXXXXX" \ --data 'format=json&data={ "shipments": [], "pickup_location": { "name": "Hello", "add": "ABC123", "city": "Delhi", "pin_code": 813210, "country": "India", "phone": "1234567890" } }'
我转换成JSON,但似乎总是无法检测格式参数。
我尝试像这样发送正文:
{ format : 'json', data : {......other parameters } }
但它说 POST 数据中缺少格式键。
const url = 'https://track.delhivery.com/api/cmu/create.json';
const headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': 'Token XXXXXXXXXXXXXXXXXX'
});
const data = {
shipments: [],
pickup_location: {
name: "Hello",
add: "ABC123",
city: "Delhi",
pin_code: 813210,
country: "India",
phone: "1234567890"
}
};
const formData = new URLSearchParams();
formData.append('format', 'json');
formData.append('data', JSON.stringify(data));
fetch(url, {
method: 'POST',
headers: headers,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
尝试上面的代码,让我看看这给出了什么输出,我认为它应该有效。