Search code examples
javascriptdjangofetch

fetch request resulting in error: Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name at HTMLInputElement.<anonymous>


Why am I getting this error? I am trying to fetch my index view to edit an object in one of my models. I don't really know what I am doing with sending the CSRF token in this way, I copied it from an example I found online, so I don't know if that is the problem. Code is below:

function edit_post(post) {

    const content_div = document.getElementById(`post-body-${post.id}`);
    content_div.innerHTML = "";

    const edit_form = document.createElement('div');
    const form_input = document.createElement('input');
    form_input.setAttribute('type', 'textarea');
    form_input.setAttribute('name', 'post-body');
    text_to_edit = post.body;
    form_input.setAttribute('value', text_to_edit);
    const save_button = document.createElement('input');
    save_button.setAttribute('type', 'submit');
    save_button.setAttribute('value', 'Save');
    save_button.addEventListener('click', () => {
        const new_body = form_input.value;
        console.log(`${new_body}`);

        fetch('/', {
            method: 'PUT',
            headers: {
                'X-CSRF TOKEN': getCookie("csrftoken")
            },
            body: body = JSON.stringify({
                post_id: post.id,
                new_body: new_body,
            })
        })
        .then(response => null)
    });

    edit_form.append(form_input);
    edit_form.append(save_button);
    content_div.append(edit_form);

}
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length == 2) return parts.pop().split(';').shift();
}

Solution

  • It maybe caused by your header in fetch request.

    1. For X CSRF TOKEN you must type 'X-CSRF-TOKEN' instead of 'X-CSRF TOKEN'
    2. To get a cookie, I suggest this function:
    function getCookie(name) {
      if (!document.cookie) {
        return null;
      }
    
      const xsrfCookies = document.cookie.split(';')
        .map(c => c.trim())
        .filter(c => c.startsWith(name + '='));
    
      if (xsrfCookies.length === 0) {
        return null;
      }
      return decodeURIComponent(xsrfCookies[0].split('=')[1]);
    }