- Forums
- laravel
- [SOLVED] message: Unauthenticated Error with Laravel API and React SPA
This is the solution for an error in laravel when attempting to access a controller and requires authentication because it fails Unauthenticated [5309], Last Updated: Mon Jun 24, 2024
edw
Sat Apr 13, 2024
0 Comments
262 Visits
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