错误[HTTP标题发送错误]:在更新Node.js中的配置文件API时将标头发送到客户端后,无法设置标头

sulc1iza  于 2023-01-16  发布在  Node.js
关注(0)|答案(1)|浏览(106)

我是Node.js的新手,遇到了一些问题。
错误[HTTP标题发送错误]:标头发送到客户端后无法设置
在新节点错误(节点:内部/错误:393:5)
在服务器响应。设置标头(节点:_http_outgoing:644:11)
在服务器响应标头(F:\项目\节点js\节点js\节点模块\表达式\库\响应. js:794:10)

exports.update_profile = async (req, res) => {
  try {
    let rules =
    {
      username: req.body.username,
      email: req.body.email,
      mobile: req.body.mobile,
      companyname: req.body.companyname,
    };

    if (req.files && req.files.Profile_images) {
      req.body['Profile_images'] = req.files.Profile_images;
    }

    const user = new User(req.body, rules);
    user.save(err => {
          if (err) {
            res.status(500).send({ message: err });
            return;
          }
        });

    let current_user = req.User;

    if (req.files && req.files.Profile_images) {
      var image_file = req.files.Profile_images;
      var image_file_name = Date.now() + '-Profile-images-' + image_file_name;
      var image_path = publicPath + '/Profile_images/' + image_file_name;
      await image_file.mv(image_path);
      if (current_user.profile_image && current_user.profile_image == '') {
        let old_path = publicPath + '/Profile_images/' + current_user.Profile_images;
        if (fs.existsSync(old_path)) {
          fs.unlinkSync(old_path);
        }
      }
    } else {
      var image_file_name = current_user.Profile_images;
    }

    await User.updateOne({
      _id: current_user._id
    }, {
      username: req.body.username,
      email: req.body.email,
      mobile: req.body.mobile,
      companyname: req.body.companyname,
      profile_image: image_file_name,
      profession: req.body.profession ? req.body.profession : ''
    });

    let userData = await User.findOne({ _id: current_user._id })
    let jwt_secret = process.env.JWT_SECRET || 'mysecret';
    let token = jwt.sign({
      data: userData
    }, jwt_secret, { expiresIn: '12h' });

    return res.status(200).send({ message: 'Profile Updated Successfully Updated', data: userData, token: token });

  } catch (error) {
    return res.status(404).send({ message: error.message });
  }
}

这是我的代码更新配置文件我可以知道我的代码有什么问题吗?

e4yzc0pl

e4yzc0pl1#

user.save()中的错误处理程序抛出错误-〉已向客户端发送500响应,但代码继续-〉ERR_HTTP_HEADERS_SENT。请更改代码:
发件人:

user.save(err => {
          if (err) {
            res.status(500).send({ message: err });
            return;
          }
        });

收件人:await user.save()
然后它会记录一些更有用的东西。

相关问题