Express.js:req.params.id 在处理 PATCH 请求的路由中未定义

问题描述 投票:0回答:1

所以我想重构 updateUser 处理程序的代码,我不希望用户在此处理程序中更改密码,只更改名称和电子邮件:

const filterdObj = (body, ...fields) => {
  const newObj = {};
  Object.keys(body).forEach(el => {
    if (fields.includes(el)) newObj[el] = body[el];
  });
  return newObj;
};

exports.updateUser = catchAsync(async (req, res, next) => {
  if (req.body.password || req.body.passwordConfirm) {
    return next(new AppError('The password cannot change in this routes'), 400);
  }
  const filteredBody = filterdObj(req.body, 'name', 'email'); 
  const updatedUser = await User.findByIdAndUpdate(req.user.id, filteredBody, {
    new: true,
    runValidators: true
  });
  res.status(200).json({
    status: 'success',
    data: {
      user: updatedUser
    }
  });
});

所以我创建了一个名为factoryController的新文件,以使更新处理程序可供其他人重用:

exports.updateOne = Type =>
  catchAsync(async (req, res, next) => {
    const doc = await Type.findByIdAndUpdate(req.params.id, req.body, {
      new: true,
      runValidators: true
    });
    if (!doc) {
      return next(
        new AppError('No document found! please check the ID correctly', 404)
      );
    }
    res.status(200).json({
      status: 'updated!',
      data: {
        doc
      }
    });
  });

为了像这样调用处理程序:

exports.updateUser = factoryController.updateOne(User);
我制作了一些将在 updateUser 之前执行的中间件:

exports.checkUserUpdate = catchAsync(async (req, res, next) => {
  if (req.body.password || req.body.passwordConfirm) {
    return next(new AppError('The password cannot change in this routes'), 400);
  }
  req.filteredBody = filterdObj(req.body, 'name', 'email'); 
  next();
});

在路由器中,我在 updateUser: 之前调用中间件:

router
  .route('/:id')
  .patch(
    authController.verifyRoutes, // Make sure the user must logged in
    userController.checkUserUpdate,
    userController.updateUser
  )

但是当我尝试更新用户时,收到 404 消息,调试后只有 ID 未定义,但主体存在:

ID: undefined
Body: { name: 'name update', password: 'somethingnew' }

我的代码有什么问题?

我的代码中的错误解决方案

javascript express undefined
1个回答
0
投票

您使用此代码更新用户

User.findByIdAndUpdate(req.user.id
req.user.id
从哪里来?

© www.soinside.com 2019 - 2024. All rights reserved.