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

使用Sample Data API提交数据失败,返回必填字段缺失错误

问题排查与解决

你的请求报错核心原因是:fetch配置中的body是空对象,没有传入已定义的myData数据,导致API无法接收到必填的email和password字段,因此返回"Required Fields Missing"错误。

修正后的代码(直接使用已定义的myData)

form.addEventListener("submit", function(e){
    const myData = 'email=sampledatapi@gmail.com&password=202020'
    e.preventDefault();
    fetch("https://sampledataapi.com/API/login", {
        method: 'post',
        headers : {"Content-Type": "application/x-www-form-urlencoded"} ,
        body: myData // 替换为空对象,传入实际的表单数据字符串
    })
    // 新增响应处理,方便查看结果或排查问题
    .then(response => response.json())
    .then(result => console.log('登录响应:', result))
    .catch(err => console.error('请求异常:', err));
})

更灵活的方案(使用URLSearchParams构建数据)

如果后续需要从表单动态获取输入值,推荐用URLSearchParams来构建符合application/x-www-form-urlencoded格式的数据,可读性和扩展性更好:

form.addEventListener("submit", function(e){
    e.preventDefault();
    // 构建表单数据
    const formParams = new URLSearchParams();
    formParams.append('email', 'sampledatapi@gmail.com');
    formParams.append('password', '202020');

    fetch("https://sampledataapi.com/API/login", {
        method: 'post',
        headers : {"Content-Type": "application/x-www-form-urlencoded"} ,
        body: formParams
    })
    .then(response => response.json())
    .then(result => console.log('登录响应:', result))
    .catch(err => console.error('请求异常:', err));
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:15:16