简体   繁体   中英

How to send data from React to Django API

I'm trying to add some data to an database with django. As frontend I use React.

Thus, fetch request is as follows:

const data = {
  name: formData.name,
  email: formData.email,
  title: formData.title,
  message: formData.message
};

fetch("/some/some_view/", {
  method: 'POST',
  headers: {
    'Accept': 'application/json, text/plain, */*',
    "Content-Type": "application/json"
  },
  body: JSON.stringify(data),
})
  .then((response) => response.json())
  .then((data) => {
  debugger;
  console.log('Success:', data);
})
  .catch((error) => {
  debugger;
  console.error('Error:', error);
});

And in Django I have view as follows:

@csrf_exempt
def some_view(request):
    if request.method == 'GET':
        return HttpResponse('Unauthorized', status=400)
    if request.method == 'POST':
        #TODO: Add security
        item = json.loads(request.POST.get('body'), object_hook=json_util.object_hook)
        pdb.set_trace()
        return HttpJsonOk()

In request.POST I get the data that I want to send as follows:

<QueryDict: {u'{"name":"dsdsd","email":"dsdsd@dsds.com","title":"dsds jflj ","message":"dlkj lksj kmsdkk fljs m"}': [u'']}>

But I expect it to be in request.POST.get('body') , but there I do not get anything.

Any idea?

request.POST contains the result of parsing request.body as form-encoded content. Note that the real request content is actually in request.body (print it out from your view to find out what it looks like).

Now your react front is posting json content, not form-encoded content, so you CAN NOT get those data from request.POST - as you can obviously tell from what the querydict looks like:

 <QueryDict: {u'{"name":"dsdsd","email":"dsdsd@dsds.com","title":"dsds jflj ","message":"dlkj lksj kmsdkk fljs m"}': [u'']}>

As you can see, the parsing failed (since it's not form-encoded), leading to the whole submitted json being used as key, with no associated value.

IOW, LinnTroll's suggestion is actually the proper solution - the one that is used by any REST framework (DRF, restless etc) FWIW -: just use request.body , period.

But I want the data in request.POST.get('body')

You cant, because there's no 'body' key in request.POST . Period.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM