Запрос на выборку привел к ошибке: Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name at HTMLInputElement.<anonymous>
Почему я получаю эту ошибку? Я пытаюсь получить представление index, чтобы отредактировать объект в одной из моих моделей. Я не совсем понимаю, что я делаю с отправкой CSRF-токена таким образом, я скопировал его из примера, который нашел в Интернете, поэтому я не знаю, в этом ли проблема. Код приведен ниже:
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();
}
Возможно, это вызвано вашим header
в запросе на выборку.
- Для X CSRF TOKEN необходимо ввести
'X-CSRF-TOKEN'
вместо'X-CSRF TOKEN'
.
- Для получения cookie, я предлагаю эту функцию:
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]);
}