[Vuejs]-How can i send a post request using vue to django without getting a 403 error?

0👍

You could use a method that involves fetching the csrf token with javascript and then passing it to the POST request as a header as mentioned here in Django documentation. In that link there is also examples about fetching the csrf token value.

Also, if the endpoint does not require this kind of protection you can disable it like in this example.

0👍

You can use something like this:

{% csrf_token %}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.13/vue-resource.min.js"></script>

<script>
    var csrf = document.querySelector('[name="csrfmiddlewaretoken"]').value;

    Vue.http.interceptors.push(function (request, next) {
        request.headers['X-CSRF-TOKEN'] = csrf;
        next();
    });

    // Or maybe
    Vue.http.headers.common['X-CSRF-TOKEN'] = csrf;
</script>

You can also use it like this, for example:

<script>
    var csrf = '{{ csrf_token }}';

    Vue.http.headers.common['X-CSRF-TOKEN'] = csrf;
    // Or other way
    // Vue.http.interceptors.push(...);
</script>

Note: I’m no django developer but gave you the basic idea, so check the doc for more info.

Leave a comment