You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js中如何设置x-access-token请求头以通过身份验证?

解决React中请求头身份验证令牌设置错误导致的未授权问题

问题核心

你需要将JWT令牌以x-access-token为键、令牌值为对应值的形式放入请求头,但当前前端代码错误使用了Authorization头,导致后端中间件无法识别令牌,返回未授权错误。

后端验证逻辑

后端通过以下中间件校验x-access-token头:

module.exports = middlewares = {
  authenticateToken: async (req, res, next) => {
    try {
      if (
        !req.headers["x-access-token"] ||
        req.headers["x-access-token"] === ""
      ) {
        return res.failed(401, "Key x-access-token not found");
      }

      const token = req.headers["x-access-token"];
      const data = jwt.verify(token, keys.JWToken);
      if (!data) return res.failed(401, "Invalid token");
      req.data = data;

      next();
    } catch (error) {
      return res.failed(500, "Internal server error", error);
    }
  },
};

前端当前代码问题

你的createPackage操作中,请求头使用了Authorization而非后端要求的x-access-token:

export const createPackage = (packageData) => async (dispatch, getState) => {
  try {
    dispatch({ type: PACKAGE_CREATE_REQUEST });

    const {
      adminLogin: { adminInfo },
    } = getState();

    const config = {
      headers: {
        "Content-Type": "application/json",
        Authorization: `${adminInfo.data.JWToken}`, // 此处用错了请求头键名
      },
    };
    const { data } = await axios.post(
      "http://localhost:8000/v1/package/add_package",
      packageData,
      config
    );
    dispatch({ type: PACKAGE_CREATE_SUCCESS, payload: data });
  } catch (error) {
    dispatch({
      type: PACKAGE_CREATE_FAILURE,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

修正方案

将请求头中的Authorization替换为x-access-token,确保键名与后端校验规则完全一致:

export const createPackage = (packageData) => async (dispatch, getState) => {
  try {
    dispatch({ type: PACKAGE_CREATE_REQUEST });

    const {
      adminLogin: { adminInfo },
    } = getState();

    const config = {
      headers: {
        "Content-Type": "application/json",
        "x-access-token": adminInfo.data.JWToken, // 修正为正确的请求头键名
      },
    };
    const { data } = await axios.post(
      "http://localhost:8000/v1/package/add_package",
      packageData,
      config
    );
    dispatch({ type: PACKAGE_CREATE_SUCCESS, payload: data });
  } catch (error) {
    dispatch({
      type: PACKAGE_CREATE_FAILURE,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

额外检查点

  • 可通过console.log(adminInfo.data.JWToken)确认是否能取到有效令牌值
  • 确保x-access-token的大小写与后端代码完全匹配(HTTP头虽不区分大小写,但严格匹配可避免潜在问题)

内容的提问来源于stack exchange,提问作者John Oliver

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:31:00