You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击按钮触发onclick函数调用本地API获取数据失败,该如何解决?

问题原因

  • 路由大小写不匹配:后端Express注册的接口路径是/Users(首字母大写),前端fetch请求的路径是/users(全小写),Express默认开启路由大小写敏感,因此请求会返回404错误。
  • 按钮默认提交行为干扰:你使用的按钮type为submit,如果该按钮处于<form>标签内部,点击后会触发表单默认提交、页面刷新,异步fetch请求会被直接中断,无法拿到返回结果。

修复步骤

  1. 统一接口路径,前后端保持大小写一致即可,比如都改成小写/users
  2. 把按钮type改成button,或者在点击事件里阻止默认行为
  3. 新增表格渲染逻辑,把接口返回的json数据渲染成页面表格

修复后的代码示例

前端代码

<!-- 按钮部分 -->
<button type="button" class="btn btn-outline-light" onclick="getUsers()">Users</button>
<!-- 用来放置生成表格的容器 -->
<div id="tableContainer"></div>

<script>
function getUsers(){
  fetch('http://localhost:3000/users')
  .then(response => response.json())
  .then(json => {
    console.log(json)
    // 调用表格渲染函数
    renderTable(json)
  })
  .catch(err => console.error('请求出错:', err))
}

function renderTable(data) {
  if (!data || data.length === 0) {
    document.getElementById('tableContainer').innerHTML = '<p>暂无数据</p>'
    return
  }
  // 生成表头
  const headers = Object.keys(data[0])
  let tableHtml = `<table border="1" cellpadding="8" cellspacing="0">
    <thead>
      <tr>${headers.map(header => `<th>${header}</th>`).join('')}</tr>
    </thead>
    <tbody>`
  // 生成表体
  data.forEach(item => {
    tableHtml += `<tr>${headers.map(header => `<td>${item[header] ?? ''}</td>`).join('')}</tr>`
  })
  tableHtml += `</tbody></table>`
  // 插入到页面
  document.getElementById('tableContainer').innerHTML = tableHtml
}
</script>

后端代码(仅修改路由部分)

// 把原来的/Users改成/users和前端保持一致
app.get('/users', function (req, res) {
  res.send(content);
})

内容的提问来源于stack exchange,提问作者Abo Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:15:03