2

I am using Django and React. I need to send a string from Django to React. I have tried using both HttpResponse and JsonResponse but both seem to be returning a response object that does not include the data.

The response object from React looks like this:

Response {type: "cors", url: "http://localhost:8000/post/", redirected: false, status: 200, ok: true, …}
   body: (...)
   bodyUsed: false
   headers: Headers {}
   ok: true
   redirected: false
   status: 200
   statusText: "OK"
   type: "cors"
   url: "http://localhost:8000/post/"
   __proto__: Response

Here is my Django

from django.http import HttpResponse, JsonResponse

def index(request):
    string1 = ""
    
    if request.method == 'POST':
        # ...processing upload...
        string1 = "Hello World"

    return HttpResponse(string1)

And my react request looks like this:

async function handleSubmit(event) {
    let formData = new FormData();
    formData.append(file)
    fetch("http://localhost:8000/post/", {
       method: "POST",
       body: formData,
       enctype: "multipart/form-data",
    }).then((res) => {
      console.log(res);
    });

How can I get the data I need (string1) included in the response object (or without the response object)? I've looked on StackOverflow and around the web and haven't found a solution. I am also not sure whether this is a problem with Django or React but it seems like a Django problem. (Also, I don't believe it is a CORS Problem as I have CORS are allowed.

Thanks

2 Answers 2

3

It does include the data, as payload, but that makes it less accessible, especially if you later plan to pass multiple items. You can wrap the result in a JSON blob:

from django.http import JsonResponse

def index(request):
    string1 = ''
    
    if request.method == 'POST':
        # … processing upload …
        string1 = 'Hello World'

    return JsonResponse({'result': string1})

In the JavaScript part, you can then interpret the response as JSON and deserialize it:

async function handleSubmit(event) {
    let formData = new FormData();
    formData.append(file)
    fetch("http://localhost:8000/post/", {
       method: "POST",
       body: formData,
       enctype: "multipart/form-data",
    }).then(response => {
      response.json().then(data => {
        console.log(data.result);
      })
    })
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that fixed it, I had tried using JsonResponse before but my mistake was the second .then(). Can't believe it was that simple.
0

It's not Django that is adding all those attributes. That's just the standard fetch Response. You can access your text data through the Response object as follows:

fetch('https://stackoverflow.com', {method: 'GET'})
   .then(res => res.text())
   .then(text => console.log(text))

In the case of JSON data, you just have to use the .json() method instead of .text():

fetch('https://stackoverflow.com', {method: 'GET'})
   .then(res => res.json())
   .then(json => console.log(json))

See the documentation for the Response object of the Fetch API: MDN

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.