简体   繁体   English

React.js “语法错误:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符”

[英]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"但我一直面临错误,即“SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列的意外字符”

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 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 page 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 might return undefined. localStorage.getItem可能返回未定义。 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');你的 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: 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\""这显然不是 json object。您可以添加如下检查条件:

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:要将 auth item 用作 JSON,首先从浏览器的 localStorage 中删除该项目,然后将保存该项目的代码更改为如下所示:

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然后将其检索为 JSON 您可以首先验证该项目是否存在,因此代码将是

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 React JS 中出现错误:SyntaxError: JSON.parse: JSON 数据的第 1 行第 1 列出现意外字符? - Getting ERROR in React JS: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data? SyntaxError:JSON.parse:React应用上JSON数据的第1行第1列的意外字符 - SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data on React app 未处理的运行时错误 SyntaxError:JSON.parse:nextjs 中 JSON 数据的第 1 行第 1 列出现意外字符 - Unhandled Runtime Error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data in nextjs 获取语​​法错误:JSON.parse:JSON 数据第 1 行第 1 列的意外字符 - Fetch SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data 来自寄存器的错误:TypeError:res 未定义/ SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符 - error from register: TypeError: res is undefined/ SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data 面对 - '未捕获(承诺)语法错误:JSON.parse:JSON 数据的第 1 行第 1 列的意外字符' - Facing - 'Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data' React SyntaxError:JSON.parse:JSON 数据第 1 行第 1 列的数据意外结束 - React SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data react-apollo 错误:[网络错误]:ServerParseError:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符 - react-apollo Error: [Network error]: ServerParseError: JSON.parse: unexpected character at line 1 column 1 of the JSON data ReactJS 和 Node.JS [JSON.parse:JSON 数据的第 1 行第 1 列的意外字符] - ReactJS and Node.JS [JSON.parse: unexpected character at line 1 column 1 of the JSON data] 在 JS 中解析给我一个 SyntaxError: JSON.parse: unexpected character - Parsing in JS gets me a SyntaxError: JSON.parse: unexpected character
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM