簡體   English   中英

401 狀態處理與訪問和刷新 Token React, Node

[英]401 status handling with access and refresh Token React, Node

當訪問令牌消失時,我不知道如何處理來自服務器的 401 狀態請求。 我在服務器端寫了 accessTokenVerify:

    require('dotenv').config();
const jwt = require("jsonwebtoken");

//  Access Token Verify
exports.accessTokenVerify = (req, res, next) => {
    if (!req.headers.authorization) return res.status(401).send({ msg: "Access Token is missing." })

    const BEARER = 'Bearer';
    const auth_token = req.headers.authorization.split(' ');
    if (auth_token[0] !== BEARER) return res.status(401).send({ msg: "Access Token is not complete." })

    jwt.verify(auth_token[1], process.env.ACCESS_TOKEN_SECRET, (err) => {
        if (err) return res.status(401).send({ msg: "Access Token is invalid." })
        next();
    })
}

我有刷新訪問令牌端點 localhost:5000/api/auth/refresh。 但是我不知道如何在客戶端實現請求,當我收到 401 狀態響應時發送刷新請求。

到目前為止我有這個:

const onSubmit = (values: Values) => {
 
    fetch("http://localhost:5000/api/posts", {
      method: "POST",
      credentials: "include",
      headers: {
        "Content-Type": "application/json",
        // 'Content-Type': 'application/x-www-form-urlencoded',
      },
 
      body: JSON.stringify({
        name: "Nazwa",
        text: "jakiś post",
        id: "341324132"
      }),
    })
      .then((response) => {
        if (response.status == 401) {
          refreshTokens();
          [and what next...]
        }
        return response.json();
      })
      .then((resp) => console.log(resp))
      .catch((err) => {
        console.log(err);
      });
  };

當 refreshTokens() 將請求發送到 /refresh 端點並設置新令牌時,但我不知道如何重新發送主請求(添加帖子)。

實際上,我自己剛剛解決了類似的情況,哈哈。 因此,為此,我強烈建議您通過 Axios 管理您的 api 請求。 從那里,您可以使用axios interceptors來解析請求的響應和錯誤,相應地處理並使用axios.request(error.config)重試請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM