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

boyjarv's avatar

401 (Unauthorized) - I am passing the bearer token in the axios.js file

Hi my endpoints are protected I have just set up state management for user register and login Here is my Repo: https://github.com/jbiddulph/spa-challenge

I have setup an axios.js file so I don't need to pass headers and I am setting my token in localstorage and in state: axios.js file:

import axios from "axios";

axios.defaults.baseURL = "http://localhost:8000/api/";
axios.defaults.headers.common["Authorization"] =
  "Bearer " + localStorage.getItem("token");

why am I getting 401 (Unauthorized) when I try to get companies from: /api/companies

please help?

Thanks

0 likes
1 reply
MohamedTammam's avatar

Add that interceptor to add your token in every request.

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

Please or to participate in this conversation.