我将令牌保存在localStorage中
localStorage.setItem('token', response.data.token)
我想在每个请求中发送令牌,我将其添加到index.js
const token = localStorage.getItem('token');
if (token) {
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}
启动项目时,如果存在令牌,则axios在每个请求中发送令牌,但是当我在启动项目后添加令牌时,axiost不发送令牌,启动项目后是否可以刷新默认配置?
答案 0 :(得分:0)
这是我对Axios请求的抽象,这允许随时添加或更改auth令牌:
import axios from 'axios';
import { API } from '../../constants';
import { store } from '../../../configureStore';
import { revokeAuthAction } from '../../../containers/Auth/actions';
export const getAuth = () => {
const sessionString = localStorage.getItem('session');
let auth;
if (sessionString) {
const session = JSON.parse(sessionString);
auth = `${session.nation}|${session.user}|${session.token}`;
}
return auth;
};
/**
* Create an Axios Client with defaults
*/
const client = axios.create({
baseURL: API.BASEURL,
headers: {
Authorization: getAuth(),
'Access-Control-Max-Age': 1728000,
},
});
/**
* Request Wrapper with default success/error actions
*/
const request = (options) => {
const onSuccess = (response) => options.raw ? response : response.data;
// console.debug('Request Successful!', response);
// If options.raw is true, return all response
const onError = (error) => {
// console.error('Request Failed:', error.config);
if (error.response) {
if (error.response.status === 401) {
// console.error('Unauthorized');
store.dispatch(revokeAuthAction());
} else {
// Request was made but server responded with something
// other than 2xx
// console.error('Status:', error.response.status);
// console.error('Data:', error.response.data);
// console.error('Headers:', error.response.headers);
}
} else {
// Something else happened while setting up the request
// triggered the error
// console.error('Error Message:', error.message);
}
return Promise.reject(error.response || error.message);
};
return client(options)
.then(onSuccess)
.catch(onError);
};
export default request;
用法:
import request from '../../../../shared/lib/request';
[...]
const create = (content) => request(
{
url: API.MY_ENDPOINT,
method: 'POST',
data: content,
});