admin管理员组文章数量:1389903
I have saved the token in localstorage: localStorage.setItem ('token', JSON.stringify (res.data)). I am trying to access the access_token
property.
JSON.parse(localStorage.getItem(token['access_token']))
It gets error: token is undefined
;
getToken = () => {
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
const url = '/oauth2/token';
axios({
method: 'post',
url,
data,
config
})
.then(res => {
if (res.status === 200) {
localStorage.setItem('token', JSON.stringify(res.data))
this.setState({
token: res.data
})
} else {
const error = new Error(res.error);
throw error;
}
}).catch(err => {
console.error(err);
alert('error');
});
}
I have saved the token in localstorage: localStorage.setItem ('token', JSON.stringify (res.data)). I am trying to access the access_token
property.
JSON.parse(localStorage.getItem(token['access_token']))
It gets error: token is undefined
;
getToken = () => {
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
const url = '/oauth2/token';
axios({
method: 'post',
url,
data,
config
})
.then(res => {
if (res.status === 200) {
localStorage.setItem('token', JSON.stringify(res.data))
this.setState({
token: res.data
})
} else {
const error = new Error(res.error);
throw error;
}
}).catch(err => {
console.error(err);
alert('error');
});
}
Share
Improve this question
edited Oct 10, 2019 at 14:52
Tony
20.2k7 gold badges41 silver badges62 bronze badges
asked Jul 29, 2019 at 9:21
UmbroUmbro
2,21412 gold badges46 silver badges107 bronze badges
2
- Try this: let tokenObj = JSON.parse(localStorage.getItem('token')); let token = tokenObj['access_token']; – Bhawana Commented Jul 29, 2019 at 9:25
- can you also share the code how you are trying to get the access token and at which point. – techipank Commented Jul 29, 2019 at 9:44
2 Answers
Reset to default 4You syntax needs to be corrected to as below
JSON.parse(localStorage.getItem('token'))['access_token']
You can use
var tokenData = JSON.parse(localStorage.getItem('token'));
console.log(tokenData.access_token);
Example how to store object in localStorage
var myObj = {
one: {
title: 'first',
id: 1,
customKey : {
first: "first",
second: "second"
}
},
two: {
title: 'second',
id: 2
},
three: {
title: 'this is the third',
id: 3
}
};
localStorage.setItem('storeObj', JSON.stringify(myObj));
var getObject = JSON.parse(localStorage.getItem('storeObj'));
本文标签: javascriptAccess the accesstoken property in localstorageStack Overflow
版权声明:本文标题:javascript - Access the `access_token` property in localstorage - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744573090a2613456.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论