How to resolve 401 error in react js using redux.?

Viewed 488

Iam trying to make an api call with redux in react js the requirement is sending phone number in the body and access token in the header which iam doing but it keeps giving me error 401 which is unauthorized access. Body of the api call requires raw data iam not sure if this is where iam doing it wrong.

Action.js

export const verifyPhoneNumber = (userdata) => {
  return async (dispatch) => {
    dispatch(fullScreenLoader(true));
    const api = new Axios();
    const response = axios.post(
      "https://theappsouk.com/api/Profile/SendVerificationSmsCode",
      {
        phone_number: userdata.pnumber,
      },
      {
        Authorization: `Bearer ${userdata.auth}`,
      }
    );
    console.log(JSON.stringify(data))
    const { data } = response;
    dispatch(fullScreenLoader(false));
    dispatch({
      type: VERIFY_PHONE_NUMBER,
      payload: data,
    });
    if (data.status) {
      dispatch({
        type: REGISTER_USER,
        payload: data,
      });
    }
  };
};

reducer.js

case VERIFY_PHONE_NUMBER:
      return {
        ...state,
        verifyPhoneNumber: action.payload,
      };

my component

export default class Comp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      number: "",
      address: "",
      error: "",
      selectedCode: "DK",
    };
  }
submitPhoneNumber = () => {
    if (this.state.number.length < 1) {
      this.setState({ error: "Phone Number is Required" });
      return;
    }
    const { number } = this.state;
    let pnumber = `${this.props.user.data.user.country_code}${number}`;
    console.log(pnumber)
    const auth = this.props.user.data.user.access_token;
    this.props.verifyPhoneNumber({
      pnumber,
      auth,
    });
  };
return (
 <form className="form bg-white p-3 mb-3">
            <div className="row">
              <div className="col-4 mr-0">
                <label>
                  <IntlMessages id="profile.emailbox.field.code" />
                </label>
                <select className="custom-select" id="inputGroupSelect01">
                  <option>{this.props.user.data.user.country_code}</option>
                </select>
              </div>
              <div className="col-8 ml-0 pl-0">
                <TextInputComponent
                  label={
                    <IntlMessages id="profile.emailbox.field.mobilenumber" />
                  }
                  type="text"
                  placeholder="Mobilnummer"
                  value={this.state.number}
                  onChange={(e) => {
                    this.handleChange(e, "number");
                  }}
                />
              </div>
            </div>
            <small className="text-danger my-0 py-0">{this.state.error}</small>
            <div className="form-group">
              <div className="divider"></div>
            </div>
            <div className="form-group mb-0 text-right">
              <button
                className="btn btn-default"
                type="button"
                onClick={this.submitPhoneNumber}
              >
                {<IntlMessages id="profile.button.update" />}
              </button>
            </div>
          </form>
)
}
3 Answers

You are using

const api = new Axios();

To declare the Axios but using axios, in the next line. Which should be

const response = api.post(
  "https://theappsouk.com/api/Profile/SendVerificationSmsCode",
  {
    phone_number: userdata.pnumber,
  },
  {
    Authorization: `Bearer ${userdata.auth}`,
  }
);

Appending Utsav's answer,

Authorization section of Axios post must be like this.

const response = api.post(
  "https://theappsouk.com/api/Profile/SendVerificationSmsCode",
  {
    phone_number: userdata.pnumber,
  },
  {
    headers: { Authorization: `Bearer ${userdata.auth}` }    
  }
);

you can use interceptors

axios.interceptors.request.use(function (req) {
    // Do something before request is sent
    
    auth = localStorage.getItem('auth') !== null ? localStorage.getItem('auth') : '';
    req.headers['Content-Type'] = 'application/json';
    req.headers['Authorization'] = 'Bearer '.concat(auth);
    req.url = 'http://www.sample.com/api/'.concat(req.url);
    return req ;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
});
Related