【问题标题】:redux not catching errorsredux 没有捕捉到错误
【发布时间】:2020-09-02 17:17:37
【问题描述】:

因此,每当加载应用程序时,它应该使用loadUser() 检查用户身份验证,我遇到的问题是,如果 localStorage 中没有令牌,服务器将不会返回任何错误(当它假设)。我查看了 auth(backend) 的代码,当没有收到令牌时它返回一个状态消息,我想知道是不是因为没有令牌不是一种错误,所以服务器没有发送错误响应?

下面是sn-ps的代码:

auth.js(后端)

const jwt = require("jsonwebtoken");

const config = require("config");

module.exports = function (req, res, next) {
  //get token from header
  const token = req.header("x-auth-token");

  // check if not token


  
  if (!token) {
    return res.status(401).json({ msg: "no token, auth denied" });
  }
  
  //verify token

  try {
    const decoded = jwt.verify(token, config.get("jwtSecret"));
    req.user = decoded.user;
    next();
  } catch (err) {
    res.status(401).json({
      msg: "token isnt valid",
    });
  }
};

App.js

const App = () => {
  useEffect(() => {
    if (localStorage.token) {
      setAuthToken(localStorage.token);
      store.dispatch(loadUser());
    }
  }, []);

auth.js 还原

export const loadUser = () => async (dispatch) => {
  console.log("from auth.js");
  if (localStorage.token) {
    setAuthToken(localStorage.token);
  }

  try {
    const res = await axios.get("/api/auth");
    console.log("inside auth.js get auth route");
    dispatch({
      type: USER_LOADED,
      payload: res.data,
    });
  } catch (err) {
    console.log("error from auth.js");
    dispatch({
      type: AUTH_ERROR,
    });
  }
};

基本上是catch(err) { //code } 里面的代码 没有被执行。

【问题讨论】:

    标签: javascript node.js react-redux


    【解决方案1】:

    我真傻,在 App.js 中添加 else 条件解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2012-03-31
      • 1970-01-01
      • 2015-08-27
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 2017-06-16
      • 2016-01-26
      • 2014-03-02
      相关资源
      最近更新 更多