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
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);
})
})
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments