I am fetching a URL like this:
fetch(url, {
mode: 'no-cors',
method: method || null,
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'multipart/form-data'
},
body: JSON.stringify(data) || null,
}).then(function(response) {
console.log(response.status)
console.log("response");
console.log(response)
})
My API expects the data to be of multipart/form-data
so I am using content-type
of this type... But it is giving me a response with status code 400.
What's wrong with my code?
This question is related to
javascript
fetch
fetch-api
I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:
curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"
The basic idea is that each part (split by string in boundary
with --
) has it's own headers (Content-Type
in the second part, for example.) The FormData
object manages all this for you, so it's a better way to accomplish our goals.
This translates to fetch API like this:
const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')
fetch('http://localhost:5001/api/v0/add', {
method: 'POST',
body: formData
})
.then(r => r.json())
.then(data => {
console.log(data)
})
Source: Stackoverflow.com