Home > Software engineering >  How to properly catch fetch request in django
How to properly catch fetch request in django

Time:05-17

I started studying django.

I have js code that calls fetch when I click the button

button = document.querySelector('.button')
button.addEventListener('click', function(){
    fetch('http://127.0.0.1:8000/test_fetch/',
{   
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        "X-Requested-With": "XMLHttpRequest",
        "HTTP_X_REQUESTED_WITH": "XMLHttpRequest"
    }
})
})

<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button >hello</button>
   
    {{ ajax }}
    <script src="{% static 'train_app/js/test_fetch.js' %}"></script>
</body>
class TestFetch(TemplateView):
    template_name = 'train_app/test_fetch.html'
    
    def get(self, request):
        ajax = request.headers
        data = {
            'name': 'Yura',
            'age': 20,
            'list': [1,2,3,4], 
            'ajax': ajax
        }
        
            
        return render(request, self.template_name, context=data)

I tried to catch the fetch request using request.META and request.headers. But they return to me information only about the first get request which is caused through urls.py.

How do I get information that this was a fetch request and its Content-Type attribute.

CodePudding user response:

In get method of 'http://127.0.0.1:8000/test_fetch/', I think you defined a render function.

So, if you want to get data through get method, you should define new api.

For example

views.py

from django.http import JsonResponse

class TestFetch(TemplateView):
    ...

def get_json_data(request):
    ajax = request.headers
    data = {
        'name': 'Yura',
        'age': 20,
        'list': [1,2,3,4], 
        'ajax': ajax
    }
    return JsonResponse(data)

urls.py

urlpatterns = [
    path("test_fetch/", TestFetch..., name="mainpage"),
    path("test_data/", get_json_data, name="get_data"),
]

test_fetch.js

button = document.querySelector('.button')
button.addEventListener('click', function(){
    fetch("{% url 'get_data' %}", // It is recommended not to use the absolute path as it will interfere with deployment.
{   
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        "X-Requested-With": "XMLHttpRequest",
        "HTTP_X_REQUESTED_WITH": "XMLHttpRequest"
    }
})
})

What is the JsonResponse

What is {% url %}?

  • Related