1

I am trying to fetch response from a Django API using react, but the key value pair which I am passing is not visible in the response.

React fetch code

handleClick(i) {
        .
        .
        .
        if (i != '=') {
         .
         .
        }
        else {
            // CODE TO FETCH FROM DJANGO API
            fetch('http://127.0.0.1:8000/solve/', {
                method: 'POST',
                body: {"expression":this.state.content}
            }).then((response)=>{ console.log(response)})
        }

}

Python Code

# Create your views here.
@api_view(["POST"])
def solveExpression(expression_json):
    try:
        math_expr = expression_json.data["expression"]
        result = eval(math_expr)
        data = {"result":result} #This is the data I want to send to reactjs
        return JsonResponse(data)
    except Exception as e:
        return JsonResponse("Error:" + str(e), safe = False)

But unfortunately the response I get doesn't have the key "result" in it.

enter image description here

Kindly correct me where I am committing the mistake as I am quiet new to reactjs.

1 Answer 1

2

fetch by default returns all the metadata related to the AJAX call that it did.

Your actual response would be inside the body property as a ReadableStream:

Try getting the body by calling .json() on the response.

Also, fetch requires a stringified body as a Request Payload. So you'll also have to call JSON.stringify with your request body

Here, give this a try:

handleClick(i) {
  ...
  if (i != '=') {
    ...
  } else {
    // CODE TO FETCH FROM DJANGO API
    fetch('http://127.0.0.1:8000/solve/', {
      method: 'POST',
      body: JSON.stringify({
        "expression": this.state.content
      })
    })
    .then((response) => response.json())
    .then(finalResponse => console.log(finalResponse))
  }

}
Sign up to request clarification or add additional context in comments.

2 Comments

When I tried the above code it's showing,[Error:Unsupported media type "text/plain;charset=UTF-8" in request.]
@StarRider, I've updated my answer. You'll also have to call JSON.stringify to the Object that you assign to body of the request. Doing that should fix this error that you're getting.

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.