I'm trying to send a POST request to an API, but receiving error 422: (Unprocessable Entity). I've tried a few things to no avail.
When I go on my web browser and browse the API through /docs I can submit data using post.
This is the sample data I'm using:
{
name: "string 1",
short_name: "string 1",
objectives: "string string",
taxonomy_id: 2,
sensor_layout_id: 2,
sensor_layout_targeted_type: "some type",
is_stratified: true,
stratification_description: "some desc",
is_sensor_cluster: true,
admin_id: 1,
id: 7
}
When I send this data through /docs on the web browser it posts correctly and I get a 200 response.
But when I go on javascript, nothing seems to work. Here's my code:
let projectFormData = {
name: 'string 2',
short_name: 'string 2',
objectives: 'string string',
taxonomy_id: 2,
sensor_layout_id: 2,
sensor_layout_targeted_type: 'some type',
is_stratified: true,
stratification_description: 'some desc',
is_sensor_cluster: true,
admin_id: 1
};
function submitProject() {
const formData = JSON.stringify(projectFormData);
fetch('http://localhost:8000/projects/', {
method: 'POST',
headers: {
Authorization: data.soundhub_api_key
},
body: formData
}).then((response) => {
response
.json()
.then((responseData) => {
const r = { status: response.status, body: responseData };
if (r.status == 200) {
console.log('sucess');
if (errorList.length > 0) {
errorList = [];
}
} else {
//failed
console.log('error');
console.log(r.body.detail);
errorList = r.body.detail;
}
})
.catch((error) => {
console.log('error ocurred');
console.error(error);
return [];
});
});
}
I am currently able to do GET requests to the server, so I know it's not an issue with my connection to the server or the API key.
I also tried turning my json into FormData using a function and passing that to the request, to no avail.
Anyone sees anything I should be doing?
JSON.stringify(formData)instead offormData, and adding"Content-Type": "application/json"to the headers.