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

JavaScript中fetch函数触发两次导致邮件列表重复展示问题咨询

两次fetch请求的原因及修复方案

1. 首要原因:表单提交未阻止默认事件

你为#compose-form绑定的onsubmit回调没有阻止浏览器默认的表单提交行为,浏览器会先同步提交一次表单,触发页面刷新,刷新后DOMContentLoaded事件再次触发默认的load_mailbox('inbox')调用,就会出现两次请求。
修复代码:

document.querySelector('#compose-form').onsubmit = (event) => {
    // 新增下面这行阻止浏览器默认表单提交
    event.preventDefault();
    fetch('/emails', {
        method: 'POST',
        body: JSON.stringify({
            recipients: document.querySelector('#compose-recipients').value,
            subject: document.querySelector('#compose-subject').value,
            body: document.querySelector('#compose-body').value
        })
    })
    .then(response => response.json())
    .then(result => {
        console.log(result);
        // 把load_mailbox移到异步回调内,确保邮件发送成功后再刷新列表
        load_mailbox('sent');
    });
}

2. 次因:load_mailbox请求路径硬编码错误

当前load_mailbox函数无论传入什么邮箱类型参数,都固定请求/emails/sent,切换邮箱时会额外触发一次请求,叠加默认加载的请求就会出现两次打印。同时你现在的写法也无法正确加载收件箱、归档箱的内容。
修复代码:

function load_mailbox(mailbox) {
    // Show the mailbox and hide other views
    document.querySelector('#emails-view').style.display = 'block';
    document.querySelector('#compose-view').style.display = 'none';

    // 先清空容器,避免后续渲染重复内容
    const emailsView = document.querySelector('#emails-view');
    emailsView.innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;

    // 用传入的mailbox参数拼接请求路径,替代硬编码的sent
    fetch(`/emails/${mailbox}`)
    .then(response => response.json())
    .then(emails => {
        console.log("Hello, world!");
        // 邮件列表渲染逻辑写在这里
    });
}

3. 其他排查方向

  • 检查JS文件是否被重复引入两次,导致DOMContentLoaded事件绑定了两次,默认的load_mailbox('inbox')执行两次
  • 打开浏览器网络面板确认两次请求的类型:如果是OPTIONS+GET两次,属于跨域预检请求,属于正常情况,只需处理GET请求的返回即可
  • 检查Django的APPEND_SLASH配置:如果开启了该配置,请求路径不带尾部斜杠时Django会自动301重定向到带斜杠的路径,导致两次请求,把fetch路径改为/emails/${mailbox}/带上尾部斜杠即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 02:45:04