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

Strapi登录接口调用异常:硬编码成功但动态传参触发验证错误

问题原因及解决方案

你的代码存在两个关键错误,导致Strapi接口无法识别必填字段:

错误1:手动序列化参数+错误嵌套请求体结构

Strapi的/auth/local接口要求请求体直接包含identifier和password字段,但你做了两个多余操作:

  1. 用JSON.stringify把参数对象转为字符串——axios会自动处理JavaScript对象的JSON序列化,手动转字符串会导致后端无法解析字段
  2. 在fetchLogin中将参数包裹在{data}里——这会让请求体结构变成{data: "序列化后的字符串"},后端找不到identifier和password这两个必填项

修正后的代码

1. 修正LoginSubmit函数(去掉JSON.stringify)

const LoginSubmit = (e) =>{
    e.preventDefault()
    const data = {
        identifier: login.email,
        password: login.password 
    }
    fetchLogin(data) // 直接传递对象,无需手动序列化
}

2. 修正fetchLogin函数(直接传递参数对象)

async function fetchLogin(data){ // 补充async关键字,原代码用了await但未标记async
    console.log(data)
    await axios
            .post(url, data) // 直接传data对象,不要嵌套在{data}中
            .then((response) => {
                console.log('Well done!');
                console.log('User profile', response.data.user);
                setUser(response.data.user)
                console.log('User token', response.data.jwt);
                setUserToken(response.data.jwt)
            })
            .catch((error) => {
                console.log('An error occurred:', error.response);
                setLoginError(error.response)
            }); 
}

额外说明

原fetchLogin函数缺少async关键字,因为内部使用了await,必须标记函数为async才能正常运行,修正代码已补上该关键字。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:36:18