E
E
Elena2021-01-13 18:09:43
JavaScript
Elena, 2021-01-13 18:09:43

How to make an interceptor in axios in react?

It seems like a simple problem, but it doesn't work at all. I can't find anything on google for react.
I need to make an axios.post request to authorize the user and have an interceptor that will substitute the header: "{ headers: { 'Authorization': `Bearer ${token}` } }" if the user is authorized. I don't understand how to implement this, if anyone knows please tell me
Here's what I could only do

export const authorize = (username, password) => {
  return axios.post(`${BASE_URL}/api/clients/token/`, {
    username,
    password
  })
    .then(res => {
      localStorage.setItem('jwt', res.data.access);
      return res;
    })
    .catch(err => console.log(err))
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dima Pautov, 2021-01-13
@Elena0394

// ./services/api.js
import axios from 'axios';

// Проверим в самом начале, есть ли токен в хранилище
const JWTToken = localStorage.getItem('jwt');

// Создать инстанс axios
const api = axios.create({
  baseURL: `${BASE_URL}/api`;
});

function apiSetHeader (name, value) {
  if (value) {
    api.defaults.headers[name] = value;
  }
};

// Если токен есть, то добавим заголовок к запросам
if (JWTToken) {
  apiSetHeader('Authorization', `Bearer ${JWTToken}`);
}

api.interceptors.request.use(config => {
  // Если пользователь делает запрос и у него нет заголовка с токеном, то...
  if (!config.defaults.headers['Authorization']) {
    // Тут пишем редирект если не авторизован
  }

  return config;
}, error => {
  return Promise.reject(error);
});

export default api;

export apiSetHeader

// ./services/sign-in.js

import api, { apiSetHeader } from './api'

export const authorize = async (username, password) => {
  try {
    const { data } = await api.post('/clients/token/', {
      username,
      password
    });
  
    localStorage.setItem('jwt', data.access);
    apiSetHeader('Authorization', `Bearer ${data.access}`);
  } catch (error) {
    console.log(error);
  }
};

Well, something like this, if nothing is confused. I wrote on my knee. There may be syntax errors))
In general, I showed the essence, but you can rewrite it for yourself and your needs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question