Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

FastAPI returns "Error 422: Unprocessable entity" when I send multipart form data with JavaScript Fetch API

$
0
0

I have some issue with using Fetch API JavaScript method when sending some simple formData like so:

function register() {  var formData = new FormData();  var textInputName = document.getElementById('textInputName');  var sexButtonActive = document.querySelector('#buttonsMW > .btn.active');  var imagesInput = document.getElementById('imagesInput');  formData.append('name', textInputName.value);  if (sexButtonActive != null){    formData.append('sex', sexButtonActive.html())  } else {    formData.append('sex', "");  }  formData.append('images', imagesInput.files[0]);  fetch('/user/register', {    method: 'POST',    data: formData,  })  .then(response => response.json());}document.querySelector("form").addEventListener("submit", register);

And on the server side (FastAPI):

@app.post("/user/register", status_code=201)def register_user(name: str = Form(...), sex: str = Form(...), images: List[UploadFile] = Form(...)):try:    print(name)    print(sex)    print(images)    return "OK"except Exception as err:    print(err)    print(traceback.format_exc())    return "Error"

After clicking on the submit button I get Error 422: Unprocessable entity. So, if I'm trying to add header Content-Type: multipart/form-data, it also doesn't help cause I get another Error 400: Bad Request. I want to understand what I am doing wrong, and how to process formData without such errors?


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>