Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DarkianZ's avatar

Axios interceptors in react, error 401

Hi guys, i can't seem to find a solution for this. I got my admin private route on the app.js, laravel as a backend. Got an axios interceptor to catch error 401, 403 and 404. The problem is when i put the code on another file and call it to the app.js , it works. But on the app.js file i always get the same error on the console. On the network sections i get error 403 from the backend with his custom message, but on error 401 i get the default one coming from laravel, even if i had defined them before.

i will show you the code and all erros on the console.

this is my app.js file


const [adminAuthenticated, setAdminAuthenticated] = useState(false);
  const [loading, setLoading] = useState(true);
  const history = useHistory();

  // Admin authentication
  useEffect(() => {
    axios.get(`/api/checkAuthenticated`).then((res) => {
      if (res.status === 200) {
        setAdminAuthenticated(true);
      }
      setLoading(false);
    });

    return () => {
      setAdminAuthenticated(false);
    };
  }, []);

  axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
    console.log(err);
    if (err.response.status === 401) {
      history.push('/');
    }
    return Promise.reject(err);
  });

  axios.interceptors.response.use(function (response) {
    console.log(response);
    return response;
  }, function (error) {
    if (error.response.status === 403)// acces denied
    {
      history.push('/')
    }
    else if (error.response.status === 404)// page not found
    {
      history.push('404')
    }
    return Promise.reject(error);
  }
  );


  let routes = (
    <>
      <Route exact path="/">
        <Homepage />
      </Route>
      <Route path="/login">
        <Login />
      </Route>
    </>
  );

  if (adminAuthenticated) {
    if(loading)
    {
        return <h1>Loading...</h1>
    }

    routes = (
      <>
      
        <Route exact path="/">
          <Homepage />
        </Route>

        <Route exact path="/admin">
          <Admin />
        </Route>
        <Route path="/admin/houses">
          <Adminhouses />
        </Route>
      </>
    );
  }



  return (
    <Router>
      <Switch>
        {routes}
        <Route exact path="/">
          <Homepage />
        </Route>

        <Route exact path="/login">
          <Login />
        </Route>
      </Switch>
    </Router>
  );

and these are the errors i get ( the first one coming from interceptor promise )

Uncaught (in promise) TypeError: error.response is undefined
    App App.js:43
    promise callback*request Axios.js:89
    method Axios.js:131
    wrap bind.js:9
    App App.js:21
    React 8
    workLoop scheduler.development.js:266
    flushWork scheduler.development.js:239
    performWorkUntilDeadline scheduler.development.js:533
    js scheduler.development.js:571
    js scheduler.development.js:633
    factory react refresh:6
    Webpack 24

the second error


Status
401
Unauthorized
VersionHTTP/1.1
Transferred1.23 kB (35 B size)
Referrer Policystrict-origin-when-cross-origin

this is my axios instance, my middleware and cors.

import axios from "axios";

axios.defaults.baseURL = "http://localhost:8000/";
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.post['Accept'] = 'application/json';

axios.defaults.withCredentials = true;

axios.interceptors.request.use(function (config) {
  const token = localStorage.getItem('auth_token');
  config.headers.Authorization = token ? `Bearer ${token}` : '';
  return config;
});

export default axios;


<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ApiAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if(Auth::check()){
            if(Auth::user()->type == '1')
            {
            
                return response()->json([
                    'status'=>200, 
                    'message'=>'Bingo !',
                ]);

            }
            else
            {
                return response()->json([
                    'status'=>403,
                    'message'=>'Acceso denegado, no eres administrador !',
                ]);
            }


        }
        else
        { 
            
            return response()->json([
            'status'=>401,
            'message'=>'Porfavor, intente conectarse de nuevo',
            ]);
        }
    }
}



<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

];

Route::middleware(['isAPIAdmin','auth:sanctum' ])->group(function () {

    // Route::get(())
    Route::get('/checkAuthenticated', function () {
        return response()->json(['message' => 'You are in', 'status' => 200], 200);
    });
}

For 403 i get the custom message, for 401 the default one set on laravel authenticate, any info on how to solve this would be great. It's been days on this thing. Thanks !!

0 likes
0 replies

Please or to participate in this conversation.