javascriptcurlbackend

Sending curl request from js


I was trying to send a request from the fetch() function to my Delhivery API from js application whose format looks like this:-

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" } }

I convert it into JSON but it seems it is always unable to detect format parameters.

I tried to send the body like this :

{ format : 'json', data : {......other parameters } }

but it says missing format key in the POST data.


Solution

  • 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));
    

    try above code and let me what output does this gives, i think it should work.