【问题标题】:Get JWT token in redux在 redux 中获取 JWT 令牌
【发布时间】:2020-12-17 19:11:14
【问题描述】:

我正在使用 JWT 来处理身份验证,并且我有一个更新新密码的功能。我的问题是如何在 UpdatePasswordAction 中将此 JWT 传递给我的服务器?实际上,我的 cookie 中有那个 JWT,但是当我将数据提交到服务器时,数据没有正确传递。我通过了吗?

无法从我的服务器检索 JWT。

  console.log(JSON.stringify(req.cookies));//  -> {} 
  console.log(req.headers.authorization);// -> undefined

在我的 User.actions.jsx 中,我要做的是获取存储在 cookie 中的令牌并传递包含当前密码、新密码和新确认密码的 updatePasswordState。

import { Cookies } from 'js-cookie';

export const UpdatePasswordAction = (updatePasswordState) => {
    return async (dispatch) => {
        try { 
           // what I do is to pass the new password and JWT to the server to handle new password update
            const token = Cookies.get('jwt');
            const res = await axios.patch(`http://127.0.0.1:3000/users/updateMyPassword`, updatePasswordState, token);
            const { data } = res;
            dispatch({ type: UserActionTypes.UPDATE_PASSWORD_SUCCESS, payload: data });
            alert('Update Password Successfully');
        } catch (error) {
            if (error.response) {
                dispatch({
                    type: UserActionTypes.UPDATE_PASSWORD_FAIL,
                    payload: error.response.data.message,
                });
                console.log(error.response.data.message);
            }
        }
    };
};

在我的服务器中,我有一个中间件来检查用户是否登录。


exports.protect = catchAsync(async (req, res, next) => {
  //Getting token and check of it's there
  let token;

  console.log(JSON.stringify(req.cookies));//  -> {} 
  console.log(req.headers.authorization);// -> undefined

  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith('Bearer')
  ) {
    token = req.headers.authorization.split(' ')[1];
  } else if (req.cookies.jwt) {
    token = req.cookies.jwt;
  }

  if (!token) {
    return next(
      new AppError('You are not logged in! Please log in to get access.', 401)
    );
  }

// rest jwt decode and verification
});

有什么办法吗?

【问题讨论】:

    标签: node.js redux jwt


    【解决方案1】:

    您没有正确地将数据发送到服务器。 axios#patch 签名是这样的:

    axios#patch(url[, data[, config]])
    

    所以你应该把它改成这样:

    await axios.patch(`http://127.0.0.1:3000/users/updateMyPassword`, updatePasswordState, {
      headers: {
        "Authorization": token
      }
    });
    

    在您的服务器端,您可以使用 req.headers.authorization 访问 Authorization 标头

    【讨论】:

      猜你喜欢
      • 2018-06-16
      • 2018-03-04
      • 2021-06-17
      • 2016-04-30
      • 2021-10-20
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 2021-01-07
      相关资源
      最近更新 更多