我只想显示数据授权用户。但是发生未定义的错误。
“ WHERE参数\“用户\”具有无效的\“未定义\”值“
如何请求仅显示当前用户?
仅要求当前用户接收数据的请求:
module.exports.getByIdAll = async function(req, res) {
try {
const query = {
where: {
user: req.user.users_id,
[Op.or]: [
{
title: {
[Op.iLike]: `%${req.query.search}%`
}
},
{
description: {
[Op.like]: `%${req.query.search}%`
}
}
]
},
offset: +req.query.pageSize * (+req.query.page - 1),
limit: +req.query.pageSize,
order: [
["title", req.query.order],
["description", req.query.order],
["createdAt", req.query.order],
["updatedAt", req.query.order]
]
};
const notebook = await Notebook.findAndCountAll(query);
res.status(200).json(notebook);
} catch (e) {
errorHandler(res, e);
}
};
用户授权:
module.exports.signIn = async function(req, res) {
const user = await User.findOne({
where: {
username: req.body.username
}
});
if (user) {
const passwordResult = bcrypt.compareSync(req.body.password, user.password);
if (passwordResult) {
const token = jwt.sign(
{
user: user
},
process.env.SECRET_OR_KEY,
{ expiresIn: 60 * 60 }
);
res.status(200).json({
token: `Bearer ${token}`
});
} else {
res.status(401).json({
message:
"Sorry, you have entered an incorrect password. Check your password again."
});
}
} else {
res.status(404).json({
message: "No user with this name was found."
});
}
};
passport.js:
module.exports = passport => {
passport.use(new JwtStrategy(opts, async (payload, done) => {
try {
const user = await User.findByPk(payload.user_id).toJSON('username user_id')
if (user) {
done(null, user)
} else {
done(null, false)
}
} catch (e) {
console.log(e)
}
}))
}
笔记本JSON格式:
{
"count": 1,
"rows": [
{
"notebook_id": 1,
"title": "fdsfsdfsd",
"description": "sdfsdfsdfsdfsdfsdfs",
"is_active": false,
"createdAt": "2019-07-09T15:55:24.193Z",
"updatedAt": "2019-07-09T15:55:24.193Z",
"users_id": 1
}
]
}
用户JSON格式:
{
"count": 2,
"rows": [
{
"user_id": 1,
"username": "admin",
"password": "$2a$10$CsuJtqwYjRSISydx5kanMOlKACRBylAbzELduHp5Brxo3weWCWdOO",
"createdAt": "2019-07-08T15:53:46.843Z",
"updatedAt": "2019-07-08T15:53:46.843Z"
},
...
]
}