NodeJS:函数不返回res.json



所以我正在为注册/注册做一个post api。如果用户成功注册,将向用户提供一个访问令牌,以便将其保存在前端。一切工作,用户名,密码与令牌一起保存在数据库中。但是访问令牌没有返回。我使用mongoDB作为我的数据库,并使用猫鼬。以下是我目前所做的:
编辑代码

const UserModel = require("../models/userModel");
var bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const registration = async (req, res) => {
try {
const { email, password } = req.body;
if (!(email && password)) {
res.status(400).send("All input is required");
}
const existingEmail = await UserModel.find({ email: email });
if (existingEmail.length === 0) {
const userToken = jwt.sign({ email: email }, process.env.SECRET, {
expiresIn: "90d",
});
let hashedPassword = await bcrypt.hash(password, 8);
const user = await UserModel.create({
email,
password: hashedPassword,
token: userToken,
});
await userRegistration.save(function (err, result) {
if (err) {
console.error(err);
} else {
console.log(result);
}
});
res.json(userToken);
} else {
res.json("email has already been registered");
}
} catch (err) {
res.json(err);
}
};
module.exports = registration;

如果我在vscode上测试雷电客户端的api,它返回{},一个空对象。请告诉我我做错了什么?

const existingEmail = await UserModel.find({ email });这一行将为您提供所有用户的数组,因为email属性没有任何内容,它将像.find({})

一样如果您正在检查用户插入的email是否已经在您的数据库中,我建议您这样做:const existingEmail = await UserModel.find({ email : email});
这将返回具有email属性值等于您在req.bodyemail : xyz@gmail.com中收到的电子邮件的文档

和在这一行const userToken = jwt.sign({ email }, process.env.SECRET, {expiresIn: "90d",});你又犯同样的错误了。你在负载中传递的对象,具有email属性,但没有值/电子邮件分配给该属性。就像email : undefined

在这里,像这样做jwt.sign({email : email}, process.env.SECRET, {expiresIn: '90d')})

所以,我在代码中犯了一个简单的错误。我试图保存未定义的userRegistration。这就是bug发生的原因。我应该更小心一点。

除了在其他答案中提到的内容外,对我来说,看起来您没有在任何地方给res.json令牌。

你的函数正在返回token,但我认为它不会去任何地方。您需要将令牌传递给res.json,而不是从函数返回。

你正在使用await以及.then(),这对我来说是错误的。你只能使用其中一个。

更新:jwt.sign返回字符串,所以userToken包含字符串。你给res.json的字符串,这是期待json。你需要传递一个对象给它。

请尝试下面提到的代码。

const UserModel = require("../models/userModel");
var bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const registration = async (req, res) => {
try {
const { email, password } = req.body;
if (!(email && password)) {
res.status(400).send("All input is required");
}
const existingEmail = await UserModel.find({ email });
if (existingEmail.length === 0) {
const userToken = jwt.sign({ email }, process.env.SECRET, {
expiresIn: "90d",
});
let hashedPassword = await bcrypt.hash(password, 8);
const user = await UserModel.create({
email,
password: hashedPassword,
token: userToken,
});
const userRegistrationResponse = await userRegistration.save();
const responseObj = {
...userRegistrationResponse,
accesstoken: `${userToken}`
};

res.json(responseObj);

} else {
res.json("email has already been registered");
}
} catch (err) {
res.json(err);
}
};
module.exports = registration;

最新更新