Reputation: 909
i want to use async await in middleware
but when i use my code this error occure
const refrsh = await User.findOne({ ^^^^^ SyntaxError: await is only valid in async function
how can i fix my code?
this is my code
exports.authenticateToken = (req, res, next) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) {
const refreshToken = req.body.refreshToken;
const refrsh = await User.findOne({
where: {id:req.body.kakaoid}
})
}
req.user = user;
next();
});
};
Upvotes: 0
Views: 119
Reputation: 3157
Use async
keyword before anonymous callback (err, user)
function.
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, async (err, user) => {
// your code...
const refrsh = await User.findOne({
where: {id:req.body.kakaoid}
});
// your code...
});
Upvotes: 0
Reputation: 12807
You need to add async
when decalre function that you want await
:
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, async (err, user) => { ...
Upvotes: 0
Reputation: 169397
Simply make the (err, user)
callback an async
function. It should work out alright in this particular case:
exports.authenticateToken = (req, res, next) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, async (err, user) => {
if (err) {
const refreshToken = req.body.refreshToken;
const refrsh = await User.findOne({
where: { id: req.body.kakaoid },
});
}
req.user = user;
next();
});
};
Upvotes: 1