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

添加FormData上传代码后页面自动刷新,请求未完成如何解决?

表单提交后自动刷新问题排查与解决

问题原因

你的代码存在两个关键错误,直接导致页面自动刷新:

  1. 请求头属性拼写错误:fetch配置里写的是header,正确属性名应为headers(复数形式),这个错误会让你设置的请求头完全不生效。
  2. FormData请求头配置错误:你手动指定了content-type: application/json,但FormData类型的请求需要multipart/form-data格式,且浏览器会自动生成带boundary分隔符的正确请求头。手动设置json类型会导致服务器无法解析请求,触发请求失败;再加上你没有捕获fetch的异常,async函数内的未处理Promise拒绝会让浏览器判定表单提交的事件处理逻辑失败,进而执行默认的表单提交行为,页面随即自动刷新。

解决方法

步骤1:修正上传接口的fetch配置

移除错误的content-type设置,同时修正header为headers(如果不需要额外请求头,可直接省略headers配置):

await fetch('http://localhost:3000/upload', {
    method: 'POST',
    body: formData,
});

若需添加其他请求头(如授权信息),保留headers但不要设置content-type:

await fetch('http://localhost:3000/upload', {
    method: 'POST',
    headers: {
        // 示例:添加授权头
        // 'Authorization': 'Bearer your-token'
    },
    body: formData,
});

步骤2:添加全局异常捕获

用try/catch包裹整个事件处理逻辑,避免任何未捕获的异常导致页面刷新:

fourthForm.addEventListener('submit', async function(event) {
    event.preventDefault();
    try {
        const username = document.getElementById('username');
        const profileImage = document.getElementById('profilePicture');

        let image = profileImage.files[0];
        let date = Date.now();
        let ending = image.name.substring(image.name.lastIndexOf('.'), image.name.length);
        let imageName = username.value + ending;
        const formData = new FormData();
        formData.append('image', image, imageName);

        USER = {
            ...USER,
            username: username.value,
            image: date + "_" + imageName
        };

        console.log(USER);

        // 修正后的上传请求
        await fetch('http://localhost:3000/upload', {
            method: 'POST',
            body: formData,
        });

        await fetch('http://localhost:3000/user', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(USER),
        });

        window.location.href = './index.html';
    } catch (err) {
        // 可添加前端错误提示,比如alert('提交失败,请重试')
        console.error('提交出错:', err);
    }
});

补充说明

  • FormData类型的请求,浏览器会自动生成正确的Content-Type头,无需手动设置,强行配置反而会破坏请求格式。
  • 当async函数作为事件监听器时,未捕获的异常会触发Promise拒绝,部分浏览器会因此执行默认事件行为(如表单提交的刷新),所以必须用try/catch捕获所有可能的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 14:00:59