简体   繁体   中英

React.js “SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data”

*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, ie "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;

localStorage.getItem might return undefined. if Item is not present in the local storage.

var _auth = localStorage.getItem('auth');

if(_auth){
    var Auth = JSON.parse(_auth)
    // Do something
}

Your localStorage.getItem('auth'); is not a JSON object,whenever you are trying to parse aa 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'))

To use the auth item as an JSON, first delete the item from localStorage of your browser then change the code that save the item to look as below:

localStorage.setItem("auth", JSON.stringify({token: resp.token}))

then to retrieve it as a JSON you could first verify if the item exists so the code would be

var auth = localStorage.getItem("auth")
if(auth){
   var authItem = JSON.parse(auth)
   var token = authItem.token
   // do something with the token
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM