Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Setting a Global Auth Header to a Auth Token With React + Axios
// api.js
// @flow
import axios from 'axios';
import { BASE_URL } from '../constants/api';
type BaseFetch = {
url: string,
}
type BasePost = {
url: string,
data: Object
}
export const api = axios.create({
baseURL: BASE_URL
});
export const baseFetch = ({ url }: BaseFetch) => api.get(url);
export const basePost = ({ url, data }: BasePost) => api.post(url, data);
// auth.js
import { api } from '../services/api';
/* ...code... */
if (json.authorized) {
// Set Axios instance to use a global header
api.defaults.headers.common['Authorization-Header'] = json.token;
await dispatch(setAuthorization(json));
dispatch(push(dashboardRoute));
}
/* ...code... */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment