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

React+Redux调用API出现401未授权错误的排查与解决

Troubleshooting 401 Unauthorized Error in React-Redux Axios API Call

Hey there, let's work through this 401 error you're hitting when trying to send the verification SMS. After looking over your code, I've spotted a couple of critical issues that are likely causing the problem, plus some adjustments to meet the API's raw data requirement.

Key Issues & Fixes

1. Incorrect Axios Headers Setup

Your current axios post request isn't formatting the authorization header correctly. Axios expects headers to be nested inside a headers object within the config parameter (the third argument of axios.post). Right now you're passing the Authorization key directly at the config root, which means the token isn't being sent properly to the API.

2. Request Body for Raw Data Requirement

The API specifies it needs raw data. While axios automatically converts JavaScript objects to JSON when sending requests, it's good to explicitly ensure the payload is formatted correctly and the Content-Type header is set to match what the API expects (usually application/json for raw JSON data).

3. Missing Error Handling

Your async action doesn't have try/catch logic. If the request fails (like returning a 401), your code will throw an uncaught error, and the loader will stay active because dispatch(fullScreenLoader(false)) won't run. Adding error handling will help you debug exactly what's going wrong.

4. Typo in Console Log

You have console.log(JSON.stringify(data)) before you define data (you destructure it after this line), which will throw a reference error.

Corrected Action.js Code

Here's the fixed version of your action with all the adjustments:

export const verifyPhoneNumber = (userdata) => {
  return async (dispatch) => {
    dispatch(fullScreenLoader(true));
    try {
      const response = await axios.post(
        "https://theappsouk.com/api/Profile/SendVerificationSmsCode",
        // Stringify the payload to ensure raw JSON format
        JSON.stringify({ phone_number: userdata.pnumber }),
        {
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${userdata.auth}`
          }
        }
      );
      const { data } = response;
      console.log(JSON.stringify(data)); // Fixed typo
      dispatch(fullScreenLoader(false));
      dispatch({ type: VERIFY_PHONE_NUMBER, payload: data });
      if (data.status) {
        dispatch({ type: REGISTER_USER, payload: data });
      }
    } catch (error) {
      dispatch(fullScreenLoader(false));
      // Log the error to debug the 401 issue
      console.error("Verification request failed:", error.response?.data || error.message);
      // Optional: Dispatch an error action to update state with the error
      // dispatch({ type: VERIFY_PHONE_NUMBER_ERROR, payload: error.message });
    }
  };
};

Additional Checks

  • Double-check that userdata.auth (the access token) is valid and hasn't expired. You can log this value before the request to confirm it's not empty or malformed.
  • Verify that the phone_number format matches what the API expects (e.g., correct country code, no extra characters). Your component seems to be combining the country code and number, but it's worth confirming the final pnumber value is correct.

By fixing the header structure, ensuring the raw data format, adding error handling, and correcting the typo, you should be able to resolve the 401 error. The catch block will also give you detailed error information if the issue persists, which will help further debug the problem.

内容的提问来源于stack exchange,提问作者Abdul Rauf Khalid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:02:56