I just spent the last two days trying to fix this error when I attempted to submit a form into a Laravel Endpoint within the api.php routes.

Error:

message: Unauthenticated

Solution: I was using the wrong axios file.

axios/common.jsx - WRONG! - DELETE THIS FILE!

axios/client.js - CORRECT

common.jsx: As you can see, its missing alot of the methods to get the token from localstorage and withCredentials, take a look at client.js below:

import axios from "axios";
export default axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL
,
    headers: {
      "Content-type": "application/json",
    }
  });

 

client.js



import axios from "axios";

axios.defaults.withCredentials = true;

const axiosClient = axios.create({
  baseURL: `${import.meta.env.VITE_API_BASE_URL}`
})

axiosClient.interceptors.request.use((config) => {
  const token = localStorage.getItem('ACCESS_TOKEN');
  config.headers.Authorization = `Bearer ${token}`
  return config;
})

axiosClient.interceptors.response.use((response) => {
  return response
}, (error) => {
  const {response} = error;
  if (response.status === 401) {
    localStorage.removeItem('ACCESS_TOKEN')
    // window.location.reload();
  } else if (response.status === 404) {
    //Show not found
  }

  throw error;
})

export default axiosClient