Search code examples
javascriptcurlxmlhttprequestmultipart

How to convert this cURL command to XMLHttpRequest in JavaScript?


I'm trying to send a request with multipart/mixed content type in JS. This is the cURL command that I'm using and it works:

curl -k -i -X POST -H "Content-Type: multipart/mixed" -H "Timestamp: 2017-
04-20'T'13:15:05" -H "AuthToken: A834F35B21E7BE50067B3E352BED" -F 
"config=@request.json;type=application/json" -F "logo=@random2.gif" 
https://pmdev.****.com:8443/core/admin/hospital/26/department/63

Here is the code I'm trying to use in JS, but it doesn't work:

let blob = new Blob([ JSON.stringify(config) ], {type:
'application/json'})

var formData = new FormData()
formData.append('config', blob)
formData.append('logo', logo)

var request = new XMLHttpRequest()
request.open(method, url)
request.setRequestHeader('Content-type', 'multipart/mixed')
request.setRequestHeader('AuthToken', authToken)
request.setRequestHeader('Timestamp', getTimestamp())
request.send(formData)

How can I fix this code?


Solution

  • Finally i managed to solve this by using axios, this is the code I have used

      let formData = new FormData()
      let blob = new Blob([ JSON.stringify(config) ], {type: 'application/json'})
      formData.append('config', blob)
      formData.append('logo', logo)
    
      axios.post(url, formData, {
        headers: {
          'AuthToken' : authToken,
          'Timestamp' : getTimestamp(),
          'Content-type': 'multipart/mixed'
        }
      })