0

I have a javascript fetch API call made to a Django backend server

const res = fetch(url, {
  credentials: 'include',
  method: 'POST',
  mode: 'same-origin',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'X-CSRFToken': csrftoken
  },
  body: JSON.stringify(requestBody),
  })
  .then((response) => response.json())
  .then((responseJson) => {
    return responseJson.movies;
  })
  .catch((error) => {
    console.error(error);
  });

If I output the requestBody on the console before using it in the request, it looks like follows

{"add-Choice":["L"],"add-Left":["1"],"add-Right":["1"],"add-Value":["100"],"add-match":["8"],"user":["siteuser1"],"csrfmiddlewaretoken":["3K89ZvofjhIL2nZQoCcxphjmXborujsaLPn2FzlYiVmiBLODWhQQiAB5BhSXkQcF"],"add":["Submit"]}

Here string "add-" is used as a form prefix on the Django side view post methode. However, on the server view side, if I print the request.POST as follow

def post(self, request, *args, **kwargs):
    print('Post request: ', request.POST)

I get the output as an empty QueryDict as follow

Post request:  <QueryDict: {}>
Internal Server Error: /matchoffers/8

The request is being sent to the correct URL and is picked up the correct view-post methode. But it fails because the request is empty.

Ivar
  • 6,138
  • 12
  • 49
  • 61
user1933205
  • 300
  • 4
  • 12
  • I suspect `requestBody` is already JSON, you don't need to stringify it again. – Barmar May 11 '21 at 19:42
  • 1
    Does this answer your question? [Django & TastyPie: request.POST is empty](https://stackoverflow.com/questions/16213324/django-tastypie-request-post-is-empty) – Ivar May 11 '21 at 19:46
  • @Ivar That was correct pointer. However, there was a slight problem with the accepted answer on that page. The data was present in request.body. However, I was having problems with accessing that data. There was some error saying that you cannot access body after reading from request's data stream. I was able to access the form data through request.data. Long story short, if you are using fetch api with form data inside fetch->body, then use request.data on the server side. – user1933205 May 11 '21 at 21:52

1 Answers1

0

If you're doing REST-based web service stuff ... you should ignore request.POST.

— Malcom Tredinnick, Django developers group

Just in case you are using DRF and you forgot to tell us

Karmavil
  • 863
  • 10
  • 13