Skip to content

Instantly share code, notes, and snippets.

@jarretmoses
Last active September 3, 2020 11:06
Show Gist options
  • Save jarretmoses/6f73caebc50e30a2ab6fd964fe4f4ae5 to your computer and use it in GitHub Desktop.
Save jarretmoses/6f73caebc50e30a2ab6fd964fe4f4ae5 to your computer and use it in GitHub Desktop.
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