0

I got the response from a nodeJS server that looks like this

token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7Il9pZCI6IjVkMmIwNzFhMWQ2MTVhMWVlMGY2NDE2YyIsImVtYWlsIjoidGVzdEB0ZXN0LmNvbSIsImZpcnN0TmFtZSI6IlRlc3QiLCJsYXN0TmFtZSI6IlRlc3QiLCJnZW5kZXIiOiJNYWxlIiwiX192IjowfSwiaWF0IjoxNTYzMTkyMTI0fQ.FlcnUAsZHesQFK8qfRWfSi-S4ay0TiUU27DkFDUaoqI"
user: {_id: "5d2b071a1d615a1ee0f6416c", email: "test@test.com", firstName: "Test", lastName: "Test",…}
email: "test@test.com"
firstName: "Test"
gender: "Male"
lastName: "Test"
__v: 0
_id: "5d2b071a1d615a1ee0f6416c"
}

I want to store it in sessionStorage using setItem function, but it's returning undefined in the console.

devbeans
  • 99
  • 1
  • 10
  • 1
    Its not valid JSON. Missing the opening parenthesis and some commas. – MauriceNino Jul 15 '19 at 12:07
  • 3
    If you want to store the whole object you need to stringify it first with JSON.stringify() – Clarity Jul 15 '19 at 12:08
  • You should call `JSON.stringify()` before putting it in `sessionStorage`. – technogeek1995 Jul 15 '19 at 12:08
  • *"I got the response from a nodeJS server that looks like this"* I assume that's a what you see when you output it in some way *after* parsing it. Because otherwise, it's not valid JSON. The property names would need to be in quotes, there'd be commas between the properties, an enclosing `{...}`, etc., etc. – T.J. Crowder Jul 15 '19 at 12:11

1 Answers1

0

you have to stringify the JSON response and store it on sessionStorage. Once retrieving first you have to get the string and convert it into JSON again.

  • *"get the string and convert it into JSON again"* ... the string **is** JSON. You mean parse the JSON to object again. JSON is a string data format – charlietfl Jul 15 '19 at 12:16
  • Nope. You should get the response -> stringify it and store in session Storage. – Vimukthi Jayasinghe Jul 15 '19 at 12:19
  • Correct. It's the second part of the answer that is not right. A javascript object is not JSON – charlietfl Jul 15 '19 at 12:21
  • Once you retrieve whatever you stored. it is stringified know. that's what I mean – Vimukthi Jayasinghe Jul 15 '19 at 12:21
  • `var testObject = { 'one': 1, 'two': 2, 'three': 3 }; // Put the object into storage localStorage.setItem('testObject', JSON.stringify(testObject)); // Retrieve the object from storage var retrievedObject = localStorage.getItem('testObject'); console.log('retrievedObject: ', JSON.parse(retrievedObject));` – Vimukthi Jayasinghe Jul 15 '19 at 12:23