NodeJS Express中axios.put请求更新按钮无响应问题排查
问题描述
我开发了一个网页留言板,可通过axios.post添加帖子、axios.delete删除帖子,但点击更新按钮时完全无响应,该按钮关联axios.put请求。我确定问题出在script.js文件中,因为使用Postman选择对应条目id发送PUT请求时,帖子可正常更新,恳请提供排查提示或思路。
核心问题排查点
- 重复ID冲突:生成的每条留言里,
<textarea>和更新按钮都使用了id="txt",DOM中ID必须唯一,document.getElementById('txt')只会返回第一个匹配的元素,导致更新时无法获取对应条目的文本内容。 - 更新按钮传参错误:更新按钮的
onclick="updateData(${txt})"传递的是文本内容,而updateData函数期望接收元素ID;如果文本包含空格或特殊字符,还会直接触发语法错误,导致函数根本无法执行。 - PUT请求地址未替换占位符:
updatePerception函数中的请求地址写死为'http://localhost:3000/perceptions/:id',没有替换为实际的条目ID,服务器无法识别要更新的资源。 - axios异步未正确处理:
addPerception、updatePerception、removePerception中直接用let res = axios.post(...)赋值,axios返回的是Promise对象,必须通过.then()或async/await处理异步结果,否则res.data无法获取正确数据,还会导致后续页面刷新时机错误。 - 无效HTML属性干扰:生成的
<textarea>里有多余的"changeTextArea(this)"属性,属于无效语法,可能干扰事件绑定逻辑。
修正建议
- 生成唯一元素ID:结合条目ID给元素命名,比如将
<textarea>的ID设为txt-${id},避免重复:
<textarea onchange="alert('Actualizado!')" id="txt-${id}">${txt}</textarea>
- 修正更新按钮传参:传递条目ID而非文本内容,同时调整
updateData逻辑:
<button class="update" aria-label="update" onclick="updateData(${id})">Editar Percepción</button>
- 修正PUT请求地址:让
updatePerception接收ID参数,替换地址中的占位符:
function updatePerception(id, text) { let payload = { text: text }; console.log('script ' + payload.text) axios.put(`http://localhost:3000/perceptions/${id}`, payload) .then(res => console.log(res.data)) .catch(err => console.error('更新失败:', err)); }
- 处理异步逻辑:所有axios请求都改用
.then()处理结果,确保数据操作完成后再刷新页面,避免依赖定时器的不稳定问题。 - 清理无效属性:移除
<textarea>中多余的无效属性,保证HTML语法正确。
完整修正后代码示例
script.js
displayPerceptions() function _(id) { return document.getElementById(id); } function displayPerceptions() { axios.get('http://localhost:3000/perceptions').then((res) => { var rows = res.data console.log(rows) _('rs').innerHTML = ''; for (var i = 0; i < rows.length; i++) { let txt = rows[i].text; let id = rows[i].id; const d = new Date(rows[i].created_at); d.addHours(1) _('rs').innerHTML += ` <article class="message"> <div class="message-header"> <p style='color:white;'>Percepción #${id}</p> <button class="delete" aria-label="delete" onclick="removeData(${id})"></button> </div> <div class="message-body"> <textarea onchange="alert('Actualizado!')" id="txt-${id}">${txt}</textarea> <button class="update" aria-label="update" onclick="updateData(${id})">Editar Percepción</button> <div><small>${d.toLocaleString()}</small></div> </div> </article> `; } }) } function addPerception(text) { let payload = { text: text }; console.log('script ' + payload.text) axios.post('http://localhost:3000/perceptions', payload) .then(res => console.log(res.data)) .catch(err => console.error('添加失败:', err)); } function updatePerception(id, text) { let payload = { text: text }; console.log('script ' + payload.text) axios.put(`http://localhost:3000/perceptions/${id}`, payload) .then(res => { console.log(res.data); displayPerceptions(); }) .catch(err => console.error('更新失败:', err)); } function removePerception(id) { axios.delete('http://localhost:3000/perceptions/' + id) .then(res => { console.log(res.data); displayPerceptions(); }) .catch(err => console.error('删除失败:', err)); } function postData(id){ let s = document.getElementById(id); addPerception(s.value); console.log(s.value); setTimeout(displayPerceptions, 1000); s.value = '' } function updateData(id){ let s = document.getElementById(`txt-${id}`); updatePerception(id, s.value); console.log(s.value); s.value = '' } function removeData(id){ removePerception(id); } Date.prototype.addHours = function(h) { this.setTime(this.getTime() + (h*60*60*1000)); return this; }
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Mi Rincón</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css"> <link rel="stylesheet" type="text/css" href="style.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script> <script defer type="text/javascript" src="script.js"></script> </head> <body> <div class="bg-img"> <section class="section"> <div class="container"> <div class="columns"> <div class="column has-text-centered offset-one-quarter"> <div class="card"> <header class="card-header has-text-centered"> <p > <h1 class="card-header-title has-text-centered title is-3 has-text-link-dark"> Mi Rincón </h1> </p> </header> <section><p class="subtitle is-inline mt-3">Publicar pensamiento:</p></section> <div class="card-content"> <div class="wrapper text-center"> <textarea id="txt" rows="3" placeholder="Escribe aquí..."></textarea> <div class="text-l"> <button class="button button is-link is-light" onclick="postData('txt')">Publicar</button> </div> </div> <div id="rs" class="wrapper"></div> </div> </div> </div> </div> </div> </section> </div> </body> </html>
内容的提问来源于stack exchange,提问作者Yisus
相关产品推荐
相关产品推荐

