【问题标题】:In my header I have the token but it is saying no token as if there is no token. but when it try it on postman it works fine. what is the problem here在我的标题中,我有令牌,但它说没有令牌,就好像没有令牌一样。但是当它在邮递员上尝试时它工作正常。这里有什么问题
【发布时间】:2020-03-04 18:04:41
【问题描述】:

这是我的操作代码:

    export const accept = (clinicianId, duration) => (dispatch, getState) => {
  axios
    .post(
      "http://localhost:5000/api/patient/authAccess",
      clinicianId,
      duration,
      tokenConfig(getState)
    )
    .then(res =>
      dispatch({
        type: ACCESS,
        payload: res.data
      })
    )
    .catch(err => {
      dispatch(
        returnErrors(err.response.data, err.response.status, "ACCESS_FAIL")
      );
    });
};

这就是我设置令牌并将其添加到我的标题的方式:

export const tokenConfig = getState => {
const token = getState().auth.token;


const config = {
  headers: {
    "Content-type": "application/json"
  }
};


if (token) {
  config.headers["x-auth-token"] = token;
}

return config;
};

这是我的 api,令牌将转到 auth 函数并授权用户:

  const { clinicianId, duration } = req.body;
  jwt.sign(
    { id: clinicianId },
    config.get("jwtSecretAccess"),
    { expiresIn: duration },
    (err, token) => {
      if (err) throw err;
      res.json({
        token
      });
    }
  );

当我检查令牌的值时,我认为 api 无法读取它?我现在不知道该怎么办。

【问题讨论】:

    标签: reactjs express redux react-redux mern


    【解决方案1】:

    您可以使用 Axios 拦截器,因为您可以为每个 http 请求添加标头

    https://dev.to/teroauralinna/global-http-request-and-response-handling-with-the-axios-interceptor-30ae

    【讨论】:

      猜你喜欢
      • 2019-12-20
      • 2022-01-18
      • 2018-08-08
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 2017-01-05
      • 2017-05-12
      相关资源
      最近更新 更多