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

如何修复Strapi评论表单组件的400 Bad Request错误

解决Strapi Reviews条目创建400 Bad Request问题

核心问题分析

你的代码存在两个不符合Strapi v4 API规范的关键问题:

  1. 请求数据结构错误:Strapi v4的创建接口要求所有字段必须包裹在data对象中,直接传递平级字段会触发400错误。
  2. 关联字段值类型错误:author(关联User)和tour(关联Tour)字段需要传入对应实体的ID,而非用户名或标题——Strapi仅通过ID识别关联关系。

具体修复步骤

1. 调整请求数据结构

修改提交的data格式,将所有字段放入data属性下:

const data = {
  data: {
    tour: tourId, // 替换为Tour的ID,而非标题
    rating: Number(rating), // 确保rating为数字类型(匹配Strapi字段设置)
    body,
    author: userId // 替换为用户的ID,而非用户名
  }
};

2. 传递正确的关联ID

  • 修改组件props:将tourTitle替换为tourId(从父组件传入旅行的ID)
  • 更新用户数据获取逻辑:从userData中获取userId而非username,示例:
    const { accessToken, userId } = userData()
    

3. 调试错误详情

在catch块中打印error.response.data,可获取Strapi返回的具体错误提示(如字段缺失、类型不匹配),快速定位问题:

catch (error) {
  console.log('Strapi错误详情:', error.response.data)
  // ...其他逻辑
}

修改后的完整handleSubmit示例

const handleSubmit = async (e) => {
  e.preventDefault()

  const data = {
    data: {
      tour: tourId,
      rating: Number(rating),
      body,
      author: userId
    }
  };

  try {
    const response = await axios.post('http://localhost:1337/api/reviews',
     data,
     {
      headers: {
        Authorization: `Bearer ${accessToken}`,
        'Content-Type': 'application/json',
      },
    })

    console.log('提交成功:', response.data)
    toast('Review created successfully!')
    setRating('')
    setBody('')

  } catch (error) {
    console.error('错误详情:', error.response.data)
    toast('Error creating review. Please try again.')
  }
};

额外检查点

  • 确认Strapi后台Reviews内容类型中,author和tour字段的关联关系配置正确(分别关联User和Tour集合)
  • 确保当前用户的JWT令牌拥有创建Reviews的权限(在Strapi的Permissions设置中开启对应权限)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 17:32:53