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

使用POST请求时因map误用导致重复创建问卷的问题及解决需求

解决重复创建问卷问题:一次性提交所有答案

我一眼就看出问题所在啦——你原来的代码在answers.map()循环里每遍历一个答案就发起一次POST请求,而且每次请求只带当前这一个答案,自然会生成和答案数量一样多的独立问卷。咱们只需要调整逻辑,把所有答案先整理好,再发起一次请求就能搞定!

修改后的完整代码

async createSurvey(streamId, title, specialization, description, answers) {
  try {
    const token = await getToken();
    const url = '/api/survey';

    // 先把所有答案转换成后端需要的answers_attributes格式
    const answersAttributes = answers.reduce((acc, answer, index) => {
      acc[index] = { answer_text: answer.answer_text }; // 若你的实际字段是answer,替换成answer.answer即可
      return acc;
    }, {});

    // 构建完整的请求体,包含所有答案
    const body = JSON.stringify({
      question: {
        title: title,
        description: description,
        specialization: specialization,
        answers_attributes: answersAttributes
      }
    });

    // 只发起一次POST请求
    const res = await fetch(BASE_URL + url, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Token token=' + token
      },
      body
    });

    console.log('server response :', res);
    return res;
  } catch (err) {
    console.log('Fetch error :', err);
    throw err; // 建议抛出错误让调用方统一处理
  }
}

关键修改点说明:

  • 移除循环内的重复请求:不再用map()遍历答案时触发请求,而是用reduce()把所有答案整理成后端需要的answers_attributes结构——比如传入两个答案时,会生成{0: {answer_text: "answer1"}, 1: {answer_text: "answer2"}}的格式。
  • 一次性构建完整请求体:把所有答案的属性一次性嵌入question对象,确保请求体包含整个问卷的完整信息。
  • 优化异步逻辑:用await替代.then(),结合try/catch统一捕获错误,代码结构更清晰,异步流程也更可控。
  • 字段名对齐:根据你给出的示例调整了字段名(从answer.answer改为answer.answer_text),如果你的实际数据字段是answer,改回对应字段即可,确保和后端接口定义匹配。

这样修改后,不管你传入多少个答案,都会只创建一个问卷,所有答案都会包含在这个问卷里啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:25:53