Search code examples
axioshttp-status-codes

axios give me error (POST /api/v1/users/token/refresh/ HTTP/1.1" 401 65) , How solve it?


in windows 10 , i'm using react-router-dom 5.2.0 and react-redux 7.2.5 and react 17.0.2. and axios 0.21.4 and WebStorm 2023.1.3 IDE.

Consider 1 - axiosInstanse.js:

import jwt_decode from 'jwt-decode';
import dayjs from 'dayjs';
import axios from 'axios';
import {updateAccessToken} from '../actions/userActions';
const baseURL = 'http://127.0.0.1:8000';

const axiosInstance = (userInfo , dispatch) => {
    const instance = axios.create({
        'mode': 'cors',
        baseURL,
        headers: {
            'Content-Type': 'application/json',
            Authorization:`Bearer ${userInfo?.access}`,
        }
    });
    instance.interceptors.request.use(async req=> {
        try {
        const user = jwt_decode(userInfo.access);
        const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 5000;
        if (!(isExpired)) {
            return req
        }

            const response = await axios.post(
                '/api/v1/users/token/refresh/' , {refresh:userInfo.refresh},
            );


        dispatch(updateAccessToken(response.data))
        req.headers.Authorization = `Bearer ${response.data.access}`;
        return req;
        } catch (error) {
           console.log(error)
        }
    });
    return instance
}

export default axiosInstance;


Consider 2 - userActions.js:

export const userFurtherInformationAction = (image, gender) => async (dispatch, getState) => {
    try {
        dispatch({ //USER FURTHER INFORMATION REQUEST
            type: USER_FURTHER_INFORMATION_REQUEST,

        });
        const {userLogin: {userInfo}} = getState();
        const formData = new FormData();
        const image_url = URL.createObjectURL(image)

        formData.append('userPicture', image);
        formData.append('sex', gender);
        // var object = {};
        // formData.forEach(function(value, key){
        //     object[key] = value;
        // });

        // var json = JSON.stringify(formData);
        // const config = {
        //     'mode': 'cors', headers: { //
        //         'Content-type': 'multipart/form-data', 'Authorization': `Bearer ${userInfo.token}`
        //     }
        // }
        const authRequestAxios = axiosInstance(userInfo,dispatch);
        const {data} = await authRequestAxios.post('/api/v1/users/complete_user_further_info/', formData);

        dispatch({ //USER FURTHER INFORMATION SUCCESS
            type: USER_FURTHER_INFORMATION_SUCCESS, payload: data,

        });
        localStorage.setItem('userInfo', JSON.stringify(data));
    } catch (error) {
        dispatch({ // USER FURTHER INFORMATION FAILED
            type: USER_FURTHER_INFORMATION_FAILED,
            payload: error.response && error.response.data.detail ? error.response.data.detail : error.message,
        });
    }
}


i expect to upload picutre --> but in my frontend -> reactjs -> axios raise error [11/Nov/2023 12:55:36] "POST /api/v1/users/token/refresh/ HTTP/1.1" 401 65

this error raise after making axiosInstance arrow function ... i guess error is at file --> axiosInstance.js


Solution

  • "POST /api/v1/users/token/refresh/ HTTP/1.1" 401 65

    Is a Http Request Authorization error which the standard states that:

    The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field containing at least one challenge applicable to the target resource.

    If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The user agent MAY repeat the request with a new or replaced Authorization header field (Section 4.2). If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user agent SHOULD present the enclosed representation to the user, since it usually contains relevant diagnostic information.

    So check that this Authorization header actually authorizes your request:

    Authorization: `Bearer ${userInfo?.access}`