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

嵌套Fetch调用createProfile API时后端无法接收数据求助

问题解决:createProfile API无法获取请求数据(req.body为undefined)

核心原因

发送JSON格式请求时未指定Content-Type头,导致后端无法正确解析请求体;同时需确保后端已正确配置JSON解析中间件。

解决方案步骤

1. 前端Fetch请求添加Content-Type头

在调用createProfile的Fetch请求中,必须显式设置Content-Type: application/json,否则后端无法识别请求体为JSON格式。

修改后的前端JS代码片段:

const resProfile = await fetch(
  'http://localhost:4000/api/createProfile',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json' // 新增请求头配置
    },
    body: JSON.stringify({
      name: name.value,
      imageid: resData.imageid
    })
  }
)

2. 确认后端已配置JSON解析中间件

确保你的Express应用在路由注册之前配置了JSON解析中间件:

const express = require('express');
const app = express();

// 必须在路由之前配置,确保所有请求都能被解析
app.use(express.json());

// 注册你的API路由
app.post('/api/createProfile', require('./your-controller-path').createProfile);

如果使用旧版body-parser,可替换为:

const bodyParser = require('body-parser');
app.use(bodyParser.json());

验证

修改后重新测试,后端的req.body即可正确获取到name和imageid参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 00:10:21