fetch请求触发Uncaught (in promise) TypeError执行fetch时无效名称报错如何解决
错误原因及修复方案
你遇到的Failed to execute 'fetch' on 'Window': Invalid name报错直接由非法的HTTP请求头字段名触发,其余还有几处代码逻辑错误,整理如下:
1. 核心报错原因
你在fetch的headers配置中写的CSRF请求头键名是'X-CSRF TOKEN',中间包含空格,HTTP协议规定请求头字段名不允许包含空格,这是直接触发报错的原因。
Django框架要求的CSRF请求头正确写法是'X-CSRFToken'(中间为连字符,无空格)。
2. 其他代码错误
- fetch配置的body字段语法错误:
body: body = JSON.stringify(...)属于非法的对象属性赋值写法,修正为body: JSON.stringify(...)即可。 - 编辑输入框类型错误:
input元素没有textarea类型,如果你需要多行输入区域,应该创建<textarea>元素而非input元素;如果只需要单行输入,把type改为text即可。 - 缺少JSON请求类型声明:你发送的是JSON格式的请求体,需要在headers中补充
'Content-Type': 'application/json',否则后端无法正确解析请求内容。
修正后的完整代码
function edit_post(post) { const content_div = document.getElementById(`post-body-${post.id}`); content_div.innerHTML = ""; const edit_form = document.createElement('div'); // 替换为textarea元素支持多行输入 const form_input = document.createElement('textarea'); form_input.setAttribute('name', 'post-body'); form_input.value = post.body; const save_button = document.createElement('input'); save_button.setAttribute('type', 'button'); save_button.setAttribute('value', 'Save'); save_button.addEventListener('click', () => { const new_body = form_input.value; console.log(`${new_body}`); fetch('/', { method: 'PUT', headers: { 'X-CSRFToken': getCookie("csrftoken"), 'Content-Type': 'application/json' }, body: JSON.stringify({ post_id: post.id, new_body: new_body, }) }) .then(response => { // 补充请求结果处理逻辑,避免静默失败 if (response.ok) { // 编辑成功后可直接替换内容无需刷新页面 content_div.innerText = new_body; } }) }); 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(); }
后端适配提示
如果你用的是Django框架,处理PUT请求时不能直接用request.POST获取参数,需要先解析request.body的JSON内容,示例:
import json def index(request): if request.method == 'PUT': data = json.loads(request.body) post_id = data.get('post_id') new_body = data.get('new_body') # 后续更新数据库等处理逻辑
内容的提问来源于stack exchange,提问作者DNL317
相关产品推荐
相关产品推荐

