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'));