简体   繁体   中英

VueJS Front-end never receives response from NodeJS backend

I'm trying to set up a login feature in my web application, where the backend uses a MongoDB database and is done with NodeJS (express), and the front-end with VueJS. However, whenever I try to send back the response from the backend to the front-end, the front-end never seems to get it. Postman also never gets the response. Here is the code:

Backend:

app.post('/login', async (req,res) => {
  let qusername;
  let qpassword;
  console.log(req.body);
  await User.find({username: req.body.username}, (err,user) => {
    if (user == null){
      return res.status(400).send('User not found');
    }
    qusername = user[0].username;
    qpassword = user[0].password;
  });
  try{
    const user = { username: qusername, password: qpassword};
    await bcrypt.compare(req.body.password, user.password, (err,res) => {
      if(err){
        res.status(500).send(err.message);
      }
      if(res){
        const accessToken = jwt.sign(user, JWT_SECRET, { expiresIn: 300}, (err, accessToken) => {
          console.log(accessToken);
          if(err) {
            res.status(500).send(err.message);
          }
        
          console.log("before");
          res.send(accessToken);
          console.log("after");
        });
      }
      else {
        res.send('Wrong password');
      }
    });
  }
  catch(e) {
    console.log(e);
    res.status(500).json({ message: e.message });
  }
});

Front-end:

    async getToken({ commit }, { user }) {
    try {
      const response = await axios.post(`${HOST}:${PORT}/login`, user);
      const authToken = response.data;
      commit("setToken", { authToken });
    } catch (e) {
      console.error(e);
    }
  }

The backend is logging the correct request body, the JWT and "before", but not "after". So the problem really occurs in res.send().

As pointed out by Danizavtz, the issue was that I had two variables named res. Changed the variable name in bcrypt.compare() from res to result and now everything works perfectly.

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