首页 > 解决方案 > 使用 Axios 时出错,但 Postman 中的响应正确

问题描述

我在后端使用 Axios 时遇到问题。这可能是一个非常简单的修复,因为我是新手。

邮递员:有效和无效凭证都收到正确响应。

Axios:收到有效凭证的正确响应,但是当输入无效凭证时运行 axios 方法的 catch 块。

authController.js:

exports.login = (req, res, next) => {
    const email = req.body.email;
    const pass = req.body.password;
    let loadedUser;

    User.findOne({ where: { email: email } })
        .then(user => {
            if(!user) {
                const error = new Error('Incorrect username or password');
                error.statusCode = 401;
                throw error;
            } else {
                loadedUser = user;
                return bcrypt.compare(pass, user.password);
            }
        })
        .then(isEqual => {
            if(!isEqual) {
                const error = new Error('Incorrect username or password');
                error.statusCode = 401;
                throw error;
            } else {
                const token = jwt.sign(
                    {
                        email: loadedUser.email,
                        userId: loadedUser.id
                    }, 
                    process.env.JWT_SECRET,
                    { expiresIn: '1hr' }
                );
                res.status(200).json({ token: token, userId: loadedUser.id });
            }
        })
        .catch(err => {
            if (!err.statusCode)
                err.statusCode = 500;
            next(err);
        });

};

app.js 中的错误处理程序。输入不正确的凭据时,似乎可以正确记录错误,即使使用 axios:

app.use((error, req, res, next) => {
    const status = error.statusCode || 500;
    const message = error.message;
    const data = error.data || 'No Data';

    console.log(status, message, data);

    res.status(status).json({message: message, data: data});
});

但是随后 axios catch 块运行,所以我没有收到 json 消息,而是收到以下错误

login(email, password) {
    const headers = {
        'Content-Type': 'application/json'
      };

      const data = JSON.stringify({
        email: email,
        password: password
      });

      axios.post('http://127.0.0.1:8080/auth/login', data, { headers })
          .then(res => console.log(res))
          .catch(err => console.log(err));

}

控制台中无效凭据的错误: 控制台错误 单击突出显示的链接会打开一个新页面,说明:“无法获取 /auth/login”,但我显然正在发出发布请求,并且我已将帖子添加到表单中(就在案子)

有什么想法我可能会错过吗?

谢谢

标签: javascriptnode.jsaxios

解决方案


Actually your code works fine but Axios will reject the promise of the call if you have the status 401. If you have a status between 200 to 300 it will resolve the promise.

There two ways to deal with this.

Check status in the catch block.

axios.post('http://127.0.0.1:8080/auth/login', data, {
    headers
  })
  .then(res => console.log(res))
  .catch(err => {
    if (err.response.status === 401) {
      //Auth failed
      //Call reentry function
      return;
    }
    return console.log(err)
  });

or change the validateStatus option;

axios.post('http://127.0.0.1:8080/auth/login', data, {
    headers,
    validateStatus: function (status) {
       return status >= 200 && status < 300 || (status === 401);
    },
  })
  .then(res => console.log(res))
  .catch(err => return console.log(err));

推荐阅读