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

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

*下面是登录和保护两个页面,附上部分代码。登录后生成令牌,如果用户获得令牌,则只有用户才能看到仪表板页面。但我一直面临错误,即“语法错误:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符”

查看源代码

 function Protected(props) {
5 |     const Cmp = props.cmp    
>7 |     var Auth =JSON.parse(localStorage.getItem('auth'))
 | ^   8 |    console.log(Auth)

查看合规

  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 页数

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 页数

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 可能 return 未定义。如果项目不存在于本地存储中。

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

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

你的localStorage.getItem('auth');不是 JSON 对象,每当您尝试使用 JSON.parse 解析非 json 对象时,您总是会收到此错误。(或者如果您的对象未定义)。所以无论你在这里做什么它总是会抛出一个错误 here.Your localStorage.getItem('Auth') is "\"4240256f255d22dd808720246a244bef1578dc00\"" which clearly isn't json object.You can add如下所示的检查条件:

const isObject = (object: unknown): object is { [key: string]: any } => typeof object === "object" && object !== null;

if(isObject(localStorage.getItem('auth')))
JSON.parse(localStorage.getItem('auth'))

要将授权项目用作 JSON,首先从浏览器的 localStorage 中删除该项目,然后将保存该项目的代码更改为如下所示:

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

然后将其作为 JSON 检索,您可以首先验证该项目是否存在,因此代码为

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