简体   繁体   中英

403 Forbidden while making ajax request to endpoint in Django

I have this endpoint to which I am making a post request from console using AJAX, its not a web page from which I am making this request.

$.ajax({
            type: 'POST',
            url: "http://127.0.0.1:8000/browse/",
            data: {csrfmiddlewaretoken: window.CSRF_TOKEN},
            success: function() {
                console.log("Success!");
            }
        })

But its giving me

VM29 jquery.min.js:2 POST http://127.0.0.1:8000/browse/ 403 (Forbidden)

The Django views code is doing nothing but returning dummy data

def Browse(request):

    data = [{'name': 'Peter', 'email': 'peter@example.org'},
            {'name': 'Julia', 'email': 'julia@example.org'}]

    return JsonResponse(data, safe=False)

urls.py

urlpatterns = [
    path('browse/', views.Browse, name = 'browse'),

Since you are not using forms currently, you can exempt from the csrf

from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
def Browse(request):

    data = [{'name': 'Peter', 'email': 'peter@example.org'},
            {'name': 'Julia', 'email': 'julia@example.org'}]

    return JsonResponse(data, safe=False)

TRY THIS

data: {"csrfmiddlewaretoken" : "{{csrf_token}}"}

instead of

data: {csrfmiddlewaretoken: window.CSRF_TOKEN},

Hope this works for you, otherwise follow this link : https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM