0

I have a SAP (written in the Svelte framework) and presented by Netlify. The business logic and data is handled by a Django app. So far I have only used GET and everything works well. But now I want to upload a file's content and use POST. When I try to POST to the Django app I get a 403 error, specifically:

WARNING:django.security.csrf:Forbidden (Origin checking failed - http://localhost:8888 does not match any trusted origins.): /test-put/

I think I have overcome any CORS issues (see this question).

The call to the Djnago API is

javascript

async function sendDataToAPI(payload) {
    let endpoint = 'http://192.168.4.28:8000/test-put/'
    const form_data = new FormData();

    form_data.append("payload", payload);

    await fetch(endpoint, {
        credentials: "same-origin",
        method: "POST",
        body: JSON.stringify({
            data: payload,
        }),
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            "X-CSRFToken": getCookie("csrftoken"),
        },
    })
    .then((response) => response.json())
    .then((result) => {
        console.log("Success:", result);
    })
    .catch((error) => {
        console.error("Error:", error);
    });
}


function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

urls.py

path('test-put/', views.TestPut.as_view()),

views.py

class TestPut(View):
    def put(self, request):
        return {}

Of course, the webpage calling the POST is NOT a Django template, so is this possible?

Psionman
  • 3,084
  • 1
  • 32
  • 65

1 Answers1

0

3 months in so I don't know if you still need this, but CORS and CSRF are related - but different things.

You can find a thorough explanation, with examples, here.

You didn't show your settings.py configuration so is hard to guess what it might be missing but Django has a setting called CSRF_TRUSTED_ORIGINS - which is different from CORS_ALLOWED_ORIGINS (both should be set if you plan on working with forms).

My guess would be on configuring CSRF_TRUSTED_ORIGINS adding http://localhost:8888 to it and double-checking your CORS_ALLOWED_ORIGINS. Both should have your localhost configured to allow requests coming in.

And just to be thorough, do remember that this setup is for LOCAL development only.