这是系统流程:
问题是当我进行新的登录时,localStorage不会使用新数据进行更新,因此我无法进行使用localStorage新用户数据的请购单。
我发现,如果我手动更新页面,则它是本地化的。
在reactjs中,我使用react-router-dom导航页面。
如何获取新的登录数据以更新localStorage?
//login
api.post('users/login', {email, password})//make log in
.then(res => {
localStorage.removeItem('user_info');// I remove the ond data from localStorage
if(res){//If api do the post
let data = JSON.stringify(res.data.data)
localStorage.setItem('user_info', data);//Save new data in localStorage
history.push('/');//Go the homepage
}
}).catch(error => {
this.setState({ noAuth: true })
console.log('error');
});
在localStorage中获取用户数据的组件:
import axios from "axios";
import { isAuthenticated } from '../../components/Util/Auth';
export const token = 'Z31XC52XC4';
// var user_info = JSON.parse(localStorage.getItem('user_info'));
// var auth_token = user_info.auth_token;
// console.log(isAuthenticated);
if (isAuthenticated()) {
var user_info = JSON.parse(localStorage.getItem('user_info'));
var auth_token = user_info.auth_token;
}
const api = axios.create({
// baseURL: 'https://url-from/api/', //PRODUÇÃO
baseURL: 'https://url-from/api/', //DESENVOLVIMENTO
headers: {
'Accept': 'application/json, text/plain, */*',
'Access-Origin': 'D',
'Authorization': `Bearer ${auth_token}`,
'Company-Token': `${token}`
}
});
// console.log(user_info);
api.interceptors.request.use(
config => {
console.log(config.headers);
console.log(user_info);
const newConf = {
...config,
headers: {
...config.headers,
'Authorization': `Bearer ${auth_token}`,
}
}
// return newConf;
},
error => Promise.reject(error)
)
export default api;
答案 0 :(得分:1)
创建Axios实例时,您传递的是“静态”值。
'Authorization': `Bearer ${auth_token}`,
如果该值不存在,它将变为
'Authorization': `Bearer undefined`,
要解决此问题,您需要向axios
添加一个拦截器,以便在每次请求时都更新该令牌的值,而不仅仅是在实例创建时。
api.interceptors.request.use(
config => {
const user_info = JSON.parse(localStorage.getItem('user_info'));
const newConf = {
...config,
headers: {
...config.headers,
'Authorization': `Bearer ${user_info.auth_token}`,
}
}
},
error => Promise.reject(error)
)
答案 1 :(得分:0)
我可以使用我的朋友JCQuintas的技巧
import axios from "axios";
import { isAuthenticated } from '../../components/Util/Auth';
export const token = 'Z31XC52XC4';
const api = axios.create({
// baseURL: 'https://url-from/api/', //PRODUÇÃO
baseURL: 'https://url-from/api/', //DESENVOLVIMENTO
headers: {
'Accept': 'application/json, text/plain, */*',
'Access-Origin': 'D',
// 'Authorization': `Bearer ${auth_token}`,
'Company-Token': `${token}`
}
});
api.interceptors.request.use(function (config) {
console.log(config);
if (isAuthenticated()) {
var user_info = JSON.parse(localStorage.getItem('user_info'));
var auth_token = user_info.auth_token;
}
config.headers.Authorization = `Bearer ${auth_token}`;
return config;
});
export default api;