ExpressJs请求将主体返回为空对象{}

ExpressJs请求将主体返回为空对象{},express,mongoose,Express,Mongoose,我想更新文档,但我的请求返回空对象{} 我经常失眠 /createProfile是注册后立即创建配置文件数据的端点 router.post('/createProfile', auth, async (req: any, res: any) => { try { const { name, gender, birthday, about } = req.body; console.log(req.body); // {} console.log(req.user

我想更新文档,但我的请求返回空对象{} 我经常失眠
/createProfile
是注册后立即创建配置文件数据的端点

router.post('/createProfile', auth, async (req: any, res: any) => {
  try {
    const { name, gender, birthday, about } = req.body;
    console.log(req.body); // {}
    console.log(req.user); // user ID

    const updatedUser = await User.findOneAndUpdate(req.user, {
      name,
      gender,
      birthday,
      about,
    });
    return res.json(updatedUser);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});
认证

和index.ts

/*eslint禁用无控制台*/
/*eslint禁用无无效*/
从“粉笔”导入粉笔;
从“cors”进口cors;
从“dotenv”导入dotenv;
从“快递”进口快递;
从“猫鼬”进口猫鼬;
从“./routes/userRouter”导入usersRouter;
dotenv.config();
const{MONGO_URI}=process.env;
mongoose.set('returnOriginal',true);
//@ts忽略
void mongoose.connect(MONGO_URI{
useNewUrlParser:true,
UseFindModify:false,
useCreateIndex:true,
useUnifiedTopology:正确,
});
mongoose.connection.on('error',console.error);
mongoose.connection.once('open',()=>

console.log(chalk.yellow.bold('MongoDB connected如果传入帖子中的内容类型不是
application/json
,那么中间件
app.use(exprss.json())
将不会读取和解析传入正文,并且
req.body
将以空结尾


因此,传入帖子上的空
req.body
几乎总是因为传入内容类型与您安装的中间件不匹配。有时您必须通过在帖子上设置正确的内容类型来解决此问题,有时您必须通过安装正确的中间件来解析您正在使用的内容类型来解决此问题.

/createprofile
的请求是如何发送的?它是表单post吗?@jfriend00我用失眠测试它,在前端我将使用axios,因此,您发送的请求数据的内容类型是什么?一个原因是
请求主体
可能是空的,因为内容类型不是JSON,因为您显示的唯一主体解析器是nstalled是
app.use(express.json());
因此,如果内容类型是
application/x-www-form-urlencoded
multipart/form data
或除
application/json
以外的任何内容,则它将不会被读取和解析,
req.body
将为空。您可以添加
console.log(req.headers)
查看传入的
内容类型是什么。我只需将内容类型:application/json添加到“失眠”和“工作”的标题中,就可以了!
const auth = (req: Request, res: Response, next: NextFunction) => {
  try {
    const token = req.header('x-auth-token');

    if (!token) {
      return res
        .status(401)
        .json({ msg: 'No authentication token, access denied' });
    }
    const { JWT_SECRET } = process.env;

    // @ts-ignore
    const verified = jwt.verify(token, JWT_SECRET);
    if (!verified) {
      return res
        .status(401)
        .json({ msg: 'No authentication token, access denied' });
    }

    // @ts-ignore
    req.user = verified.id;
    next();
  } catch (err) {
    return res.status(500).json({ error: err.message });
  }
};