How to use Django JsonResponse and JavaScript fetch

I’m using fetch and then trying to return some json with this: return JsonResponse({"data1": 1, "data2": 2})

In views.py:

@csrf_exempt
def test(request):
    if request.method == "PUT":
        # this json is not in the response, see comment in JavaScript
        # how do I send json so I can use it with fetch and do somethig with the data?
        return JsonResponse({"data1": 1, "data2": 2})
    else:
        # this sends and json is displayed in browser if request is GET
        return JsonResponse({"data1": 1, "data2": 2})

In my client.js:

const test = document.getElementById("test")
test.addEventListener("click", runTest)

function runTest(e) {
  fetch("/test", {method: "PUT"})
  .then( res => console.log(res))
  // Response { type: "basic", url: "http://localhost:8000/test", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false }
  .catch( err => console.log(err))

  e.preventDefault()
}

How do you send json with Django so you can use the json with Javascript to do things?

I believe the issues lies in the json parsing from the response. Try parsing just the res.body of the response, or using res.json() method to get parsed json.

I tried JSON.parse(res.body) which results in the same SyntaxError.
res.json() does not cause an error but the json I’m trying to send is not in the body, res.body.likes = undefined.

I edited my question to clarify the problem I’m having.

When I used res.json() i tried to access my data with res.body.likes which is undefined. The correct way I found is just res.likes.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.