javascript - 创建登录时,到达一个空对象
问题描述
空对象来登录。使用注册,在登录的相似性中完成,所以一切正常。通过 Postman 发送请求,您可以注册一个用户并检查该用户是否存在于数据库中。当您发送登录请求而不是令牌时,一条消息来自最后一个块“else”“未找到具有此类电子邮件地址的用户”。
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const keys = require('../config/keys');
module.exports.login = async function (req, res) {
console.log('req.body', req.body); //Empty object {}
const candidate = await User.findOne({
email: req.body.email
});
if (candidate) {
const passwordResult = bcrypt.compareSync(req.body.password,
candidate.password);
if (passwordResult) {
const token = jwt.sign({
email: candidate.email,
userId: candidate._id
}, keys.jwt, {expiresIn: 60 * 60});
res.status(200).json({
token: `Bearer ${token}`
})
} else {
res.status(401).json({
message: 'Passwords do not match'
})
}
} else {
console.log(req.body.email);
console.log(candidate);
res.status(404).json({
message: 'User with such email address not found'
})
}
};
module.exports.register = async function (req, res) {
console.log('req.body', req.body);
const candidate = await User.findOne({
email: req.body.email
});
if (candidate) {
res.status(409).json({
message: "User with this email address already exists"
})
} else {
const salt = bcrypt.genSaltSync(10);
const password = req.body.password;
const user = new User({
email: req.body.email,
password: bcrypt.hashSync(password, salt)
});
try {
await user.save();
res.status(201).json(user)
} catch (e) {
}
}
};
![注册正常] ( https://imgur.com/a/9T5vRMD )
!【无法正常登录】(https://imgur.com/a/rQOiw2w)“一定是token,因为这个用户已经存在”
解决方案
我自己找到了答案。我使用“x-form-urlencoded”,登录工作正常,我得到一个有效的令牌。显然问题出在 Postman 的内部实现中,因为借助“rav”输入的数据也应该是有效的。
推荐阅读
- javascript - 为什么在检查时跳过了函数并且未定义 onclick,尽管在脚本中定义了?
- css - 如何在 MUI Grid 中有不同的水平和垂直间距?
- python - 分页不适用于我的 Django 休息框架项目,我正在使用通用视图
- javascript - 尽管 URL 正确,Angular 路由器仍无法加载我的组件
- c# - .Net Core 控制台应用程序发布未在发布文件夹中创建任何文件
- marklogic - 为什么 MarkLogic 肯定会在 XML 文档中存储无效字符?
- hyperledger-fabric - 如何解决./byfn.sh -m 生成问题?
- docker - 复制或添加命令未在 docker hub 上执行
- postgresql - docker-compose 中的 Postgres 找不到/挂载 /etc/postgresql/postgres.conf
- python - png 文件无法在具有非 PlateCarree 投影的地图上正确显示