*Here below are two pages login and protected and partial code is also attached. After login a token is generated, if user gets token then only user can see dashboard page. But i have been facing error, i.e "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"
view source
function Protected(props) {
5 | const Cmp = props.cmp
>7 | var Auth =JSON.parse(localStorage.getItem('auth'))
| ^ 8 | console.log(Auth)
view complied
5623 | function Protected(props) {
5624 | const Cmp = props.cmp;
> 5625 | var Auth = JSON.parse(localStorage.getItem('auth'));
| ^ 5626 | console.log(Auth);
5627 | return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
5628 | __self: this,
Login.js page
export default class LoginScreen extends Component {
login(){
console.log("state", this.state)
fetch('http://127.0.0.1:8000/api/account/login',{
method:'POST',
body:JSON.stringify(this.state),
headers:{
'Content-type': 'application/json; charset=UTF-8',
},
}).then((result)=>{
result.json().then((resp)=>{
console.log(resp.token);
localStorage.setItem("auth", JSON.stringify(resp.token))
})
})
}
..........................
protected.js page
import React from "react";
import { Redirect } from "react-router-dom";
function Protected(props) {
const Cmp = props.cmp
var Auth =JSON.parse(localStorage.getItem('auth'))
console.log(Auth)
return <div> { Auth ? <Cmp/> : <Redirect to="/"/>}
</div>
}
export default Protected;
Your localStorage.getItem('auth'); is not a JSON object,whenever you are trying to parse a a non-json object using JSON.parse you will ALWAYS get this error.(or if your object is undefined).So no matter what you do here it always will throw an error here.Your localStorage.getItem('Auth') is "\"4240256f255d22dd808720246a244bef1578dc00\""
which clearly isn't json object.You can add a check condition like below:
const isObject = (object: unknown): object is { [key: string]: any } => typeof object === "object" && object !== null;
if(isObject(localStorage.getItem('auth')))
JSON.parse(localStorage.getItem('auth'))