Sam*_*nti 6 javascript jwt reactjs redux axios
这是一个非常奇怪的问题!我正在尝试构建一个登录表单,它在localstorage. 其他表单然后使用该令牌来发布请求。我可以console.log很好地看到令牌,但有时(例如 5 次中有 3 次),当我设置时localstorage.getitem('idToken'),它显示为空。当我console.log(idToken)从我的loginUser()函数中删除 时,这种行为最明显地发生(actions.js 文件中的代码 - 下面给出)。我究竟做错了什么?我的应用程序是使用 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))
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 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);
});
});
Run Code Online (Sandbox Code Playgroud)
这个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);
});
}
Run Code Online (Sandbox Code Playgroud)
我的智商不行了!请帮忙!
将您的令牌逻辑(即localStorage.getItem('idToken');)移动到导出的函数中,它应该可以工作
export default (async function showResults(values, dispatch) {
let token = localStorage.getItem('idToken');
const AuthStr = 'Bearer '.concat(token);
let headers ={
headers: { 'Content-Type':'application/json','Authorization' : AuthStr
}
};
axios.post(BASE_URL + 'human/new', values, headers)...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15489 次 |
| 最近记录: |