简体   繁体   中英

Accessing bearer token from axios

What code can I use to access a bearer token that's been stored in localStorage?

const apiClient = axios.create({
  baseURL: 'http://localhost:5000/api/v1',
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'.
    Authorization: ???
  }
});

I'm having trouble sending auth headers using a axios Service. When I hardcode the existing bearer token it works, but how can I dynamically access that for each user as it changes?

This is what worked! Thanks to DigitalDrifter for showing me the getItem function in localStorage.

I've been storing the bearer token in 'user' state, so I retrieved the object, parsed it, then inserted it into the Authorization header.

const user = JSON.parse(localStorage.getItem('user'));
const token = user.token;

const apiClient = axios.create({
  baseURL: 'http://localhost:5000/api/v1',
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    Authorization: `Bearer ${token}`
  }
});

A request interceptor can be used to set the Authorization header prior to each outgoing request.

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    let token = localStorage.getItem('bearer_token')

    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }


    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM