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

使用Thunder Client调用API遇400错误,修改后数据刷新丢失

API调用400错误与页面数据丢失修复方案

问题根源分析

1. 400 Bad Request错误原因

  • API请求格式不符:POST请求的body将数据嵌套在newScore对象中,但目标API要求直接传递{user, score}结构的对象,导致接口无法解析请求。
  • 本地数组更新错误:scores.push(user, score)会把用户名和分数作为两个独立元素推入数组,而非一个包含user和score属性的对象,后续渲染时无法读取正确属性。

2. 页面刷新数据丢失原因

  • 全局数组未同步API数据:getScores函数中声明了局部变量scores,并未更新全局的scores数组,导致页面始终使用本地初始化的空数组或旧数据。
  • 渲染函数未支持外部数据传入:renderScores函数没有接收参数的逻辑,即使getScores传递了API返回的数据,也无法替换全局数组进行渲染。

修正后的完整代码

const form = document.querySelector('.form');
const refresh = document.querySelector('.refresh-button');
export const scores = [];

// 页面加载时先拉取API数据
getScores();

// 事件监听
form.addEventListener('submit', (e) => {
  e.preventDefault();
  saveScore();
});

refresh.addEventListener('click', (e) => {
  e.preventDefault();
  getScores();
});

function renderScores(scoreData) {
  const scoreList = document.querySelector('.result-list');
  scoreList.innerHTML = '';
  // 优先使用传入的API数据,没有则用全局数组
  const displayScores = scoreData || scores;
  displayScores.forEach((score) => {
    const li = document.createElement('li');
    li.innerHTML = `${score.user} : ${score.score}`;
    scoreList.appendChild(li);
  });
}

async function getScores() {
  const savedScores = 'https://us-central1-js-capstone-backend.cloudfunctions.net/api/games/Zl4d7IVkemOTTVg2fUdz/scores/';
  const receivedScores = await fetch(savedScores);
  const api = await receivedScores.json();
  // 更新全局scores数组为API返回的数据
  scores.length = 0; // 清空原有数据
  scores.push(...api.result);
  renderScores();
}

async function saveScore() {
  const user = document.querySelector('.fullname').value;
  const score = document.querySelector('.thescore').value;
  const newScore = {
    user,
    score: Number(score), // 确保score是数字类型,符合API要求
  };
  
  try {
    const response = await fetch('https://us-central1-js-capstone-backend.cloudfunctions.net/api/games/Zl4d7IVkemOTTVg2fUdz/scores/', {
      method: 'POST',
      body: JSON.stringify(newScore), // 直接传递{user, score}结构
      headers: {
        'Content-type': 'application/json; charset=UTF-8',
      },
    });
    
    if (!response.ok) throw new Error('提交失败');
    // 提交成功后清空表单
    form.reset();
    // 重新拉取最新数据
    await getScores();
  } catch (err) {
    console.error(err);
  }
}

关键修改点说明

  • POST请求格式修正:将JSON.stringify({newScore})改为JSON.stringify(newScore),直接传递符合API要求的结构。
  • 本地数组更新修正:替换scores.push(user, score)为后续通过getScores从API拉取数据更新全局数组,避免本地与API数据不一致。
  • 全局数组同步:在getScores中清空全局数组并推入API返回的所有数据,确保本地数据与API一致。
  • 渲染函数优化:支持传入外部数据,优先使用API返回的数据进行渲染,同时页面加载时自动拉取API数据。
  • 数据类型修正:将score转为数字类型,避免字符串格式可能导致的API验证问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:15:39