这是一个非常奇怪的问题!我试图构建一个登录表单,它在localstorage
中设置一个JWT标记。其他表单随后使用该标记来发布请求。我可以在我的console.log
中很好地看到该标记,但有时(像5次中的3次),当我在设置localstorage.getitem('idToken')
时,当我从loginUser()
函数(actions.js文件中的代码-如下所示)中删除console.log(idToken)
时,这种行为最明显。我做错了什么?我的应用是使用React/Redux构建的。
操作.js
export function loginUser(creds) {
const data = querystring.stringify({_username: creds.username, _password: creds.password});
let config = {
method: 'POST',
headers: { 'Content-Type':'application/x-www-form-urlencoded' },
body: data
};
return dispatch => {
// We dispatch requestLogin to kickoff the call to the API
dispatch(requestLogin(creds));
return fetch(BASE_URL+'login_check', config)
.then(response =>
response.json().then(user => ({ user, response }))
).then(({ user, response }) => {
if (!response.ok) {
// If there was a problem, we want to
// dispatch the error condition
dispatch(loginError(user.message));
return Promise.reject(user)
} else {
localStorage.setItem('idToken', user.token);
let token = localStorage.getItem('idToken')
console.log(token);
// if I remove this log, my token is returned as null during post.
dispatch(receiveLogin(user));
}
}).catch(err => console.log("Error: ", err))
}
}
这是我的POST请求:
import axios from 'axios';
import {BASE_URL} from './middleware/api';
import {reset} from 'redux-form';
let token = localStorage.getItem('idToken');
const AuthStr = 'Bearer '.concat(token);
let headers ={
headers: { 'Content-Type':'application/json','Authorization' : AuthStr }
};
export default (async function showResults(values, dispatch) {
console.log(AuthStr);
axios.post(BASE_URL + 'human/new', values, headers)
.then(function (response) {
console.log(response);
alert("Your submit was successful");
//dispatch(reset('wizard'));
}).catch(function (error) {
console.log(error.response);
alert(error.response.statusText);
});
});
此GET
请求每次都有效,顺便说一句:
getHouses = (e) => {
let token = localStorage.getItem('idToken') || null;
const AuthStr = 'Bearer '.concat(token);
axios.get(BASE_URL + 'household/list', { headers: { Authorization: AuthStr } }).then((response) =>
{
let myData = response.data;
let list = [];
let key =[];
for (let i = 0; i < myData._embedded.length; i++) {
let embedded = myData._embedded[i];
list.push(embedded.friendlyName);
key.push(embedded.id);
}
this.setState({data: list, key: key});
})
.catch((error) => {
console.log('error' + error);
});
}
我已经无计可施了!请帮帮我!
4条答案
按热度按时间nhaq1z211#
这个
localStorage.setItem()
是一个异步任务,有时你运行let token = localStorage.getItem('idToken')
刚好在setItem之后就会失败,所以你得到一个null,所以请把getItem
的操作推迟一些,试一下,情况会有所不同:x9ybnkn62#
将令牌逻辑(即
localStorage.getItem('idToken');
)移动到导出的函数中,它应该可以工作vawmfj5a3#
在localstorage中设置一个键值,然后它在下一行立即返回null,这是不可能的。
仅当
user.token
值为空时才会发生这种情况。这里的情况可能是你的thennable函数没有返回值给你的next函数,就像这样:
nhn9ugyo4#
创建一个返回值或默认值的函数