UnhandledPromiseRejectionWarning:需要数据和盐参数

UnhandledPromiseRejectionWarning: data and salt arguments required

问题: 我在尝试注册新用户时一直收到标题错误 在使用邮递员时不知道为什么。

此外,代理问题:无法代理请求 /api/auth/register?hello&world 从 localhost:3000 到 http://localhost:8080/.

我尝试通过代理解决的事情是 在包 json.

中添加 "secure": false

我的auth.js文件:

exports.postRegister = async (req, res, next) => {
  // User object
  const newUser = {
    username: req.body.username,
    password: req.body.password,
  };
  // Check if user exists
  try {
    const user = await User.findOne({ username: newUser.username });
    if (user) {
      const error = new Error("Username already taken.");
      error.statusCode = 422;
      return next(error);
    }
  } catch (error) {
    error.statusCode = error.statusCode || 500;
    next(error);
  }

  // creating a hash from the given password
  bcrypt.genSalt(12, (err, salt) => {
    if (err) {
      return next(err);
    }
    bcrypt.hash(newUser.password, salt, null, async (err, hash) => {
      if (err) {
        return next(err);
      }
      try {
        // set hashed password as the password field in newUser object.
        newUser.password = hash;

        // Save newUser
        const createdUser = new User(newUser);
        await createdUser.save();

        // Create jwt token and send
        const token = await genToken(createdUser._id, createdUser.username);
        res.status(201).json({
          success: true,
          token,
        });
      } catch (err) {
        err.statusCode = err.statusCode || 500;
        next(err);
      }
    });
  });
};

Server.js 文件:

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const helmet = require("helmet");
const cors = require("cors");

require("dotenv").config();

const mailRoutes = require("./routes/mail");
const authRoutes = require("./routes/auth");

const app = express();

app.use(bodyParser.json());
app.use(helmet());
app.use(cors());

// Routes
app.use("/api/mail", mailRoutes);
app.use("/api/auth", authRoutes);

app.use((error, req, res, next) => {
  console.log(error.message);
  res.status(error.statusCode).json({
    error: true,
    messages: [error.message],
  });
});

mongoose.connect(process.env.DB_URI, (err) => {
  if (err) {
    console.log(err);
  } else {
    console.log("DB Connected");
  }
});

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
  console.log(`Server has started at ${PORT}`);
});

好的,对于面临同样问题的任何人 - 我已经解决了。 从箭头函数更改为常规函数。 显然 bcrypt 不接受箭头函数

所以代替:

bcrypt.hash(newUser.password, salt, async => (err, hash){}...

这样做:

bcrypt.hash(newUser.password, salt, async function (err, hash){}...