从js发送curl请求

问题描述 投票:0回答:1

我试图将来自 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 数据中缺少格式键。

javascript api curl backend
1个回答
0
投票
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));

尝试上面的代码,让我看看这给出了什么输出,我认为它应该有效。

© www.soinside.com 2019 - 2024. All rights reserved.