I am trying to send form data to my API hosted on heroku. On the API I had captured for empty input fields errors. It seems that I am sending data correctly (in my opinion). But I keep on receiving this error message which I know is a response from the API as it is a custom error:
{
"message": {
"typeofincident": "Type field is required"
}
}
Below is my javascript code:
function postIncident(e) {
e.preventDefault();
let token = sessionStorage.getItem('token');
let formdata = new FormData();
formdata.append("typeofincident", 'typeofincident', document.getElementById('record_type').value);
formdata.append("description", document.getElementById('description').value);
formdata.append("location", document.getElementById('location').value);
formdata.append('file', document.getElementById("media").files[0]);
fetch('https://issaireporterv2.herokuapp.com/api/v2/incidents', {
method: 'POST',
body: formdata,
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/x-www-form-urlencoded',
'content-type': 'multipart/form-data'
}
})
.then(res => res.json())
.then(data => {
if (data.Message) {
alert(data.Message)
} else {
alert(data.Error)
}
})
}
The request payload is as follows:
------WebKitFormBoundaryPoo9tZT7joBLu8YB
Content-Disposition: form-data; name="typeofincident"
------WebKitFormBoundaryPoo9tZT7joBLu8YB
Content-Disposition: form-data; name="description"
theft
------WebKitFormBoundaryPoo9tZT7joBLu8YB
Content-Disposition: form-data; name="location"
Latitude: -1.2094403999999999 Longitude: 36.8949247
------WebKitFormBoundaryPoo9tZT7joBLu8YB
Content-Disposition: form-data; name="file"; filename="user view.png"
Content-Type: image/png
------WebKitFormBoundaryPoo9tZT7joBLu8YB--
Can anyone assist where I am wrong? Thanks!
You set the Content-Type
twice.
Once you claimed it was application/x-www-form-urlencoded, which it isn't.
Then you claimed it was multipart/form-data, but you didn't specify the boundary ( WebKitFormBoundaryPoo9tZT7joBLu8YB
… not that you can know what boundary will be generated for you) so it couldn't be parsed.
Don't override the fetch
APIs generated Content-Type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.