简体   繁体   中英

SyntaxError: await is only valid in async function how can i use async?

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();
              });
            };

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();
  });
};

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...
});

You need to add async when decalre function that you want await :

 jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, async (err, user) => { ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM