在 ReactJS 中使用 fetch 时,JSON 中位于位置 0 的意外令牌 I

Posted

技术标签:

【中文标题】在 ReactJS 中使用 fetch 时,JSON 中位于位置 0 的意外令牌 I【英文标题】:Unexpected token I in JSON at position 0 while using fetch in ReactJS 【发布时间】:2022-01-16 02:08:42 【问题描述】:

我正在尝试获取登录 API。 API 在后端服务器上运行良好,但是当我尝试从前端使用 API 时,它会显示错误 Unexpected token I in JSON at position 0

下面是代码

import React,  useState  from "react";
import  useNavigate  from "react-router-dom";

const LoginPage = (props) => 

let navigate = useNavigate();

const [credentials, setCredentials] = useState(email:"",password:"");


const onChange = (e) => 
    setCredentials( ...credentials, [e.target.name]: [e.target.value])
    //  console.log(credentials);



const handleSubmit = async(e) => 

    e.preventDefault();
    const response = await fetch("http://localhost:5000/api/login", 
      method: "POST",
      headers: 
        "Content-Type": "application/json",
      ,
      body: JSON.stringify(
        email: credentials.email,
        password: credentials.password,
      ),
    );
    const json = await response.json();
    console.log(json)

    


const goToSignUp = () => 
   navigate("/signup");



  return (
    <>
  <div className="container my-5">
    <div id="loginbody">
      <div className="mt-3">
        <h2 className="my-3 display-3">Login Here</h2>
        <form className="login-form p-5" onSubmit=handleSubmit>
          <div className="mb-3">
            <label htmlFor="exampleInputEmail1" className="form-label">
              Email address
            </label>
            <input
              type="email"
              className="form-control"
              id="email"
              name="email"
              value=credentials.email
              aria-describedby="emailHelp"
              onChange=onChange
            />
            <div id="emailHelp" className="form-text">
              We'll never share your email with anyone else.
            </div>
          </div>
          <div className="mb-3">
            <label htmlFor="exampleInputPassword1" className="form-label">
              Password
            </label>
            <input
              type="password"
              className="form-control"
              id="password"
              name="password"
              value=credentials.password
              onChange=onChange
            />
          </div>
          <div className="d-grid gap-2 my-4 col-6 mx-auto">
          <button type="submit" className="btn btn-success" >
            Submit
          </button>
          </div>
          <hr />
        <div className="mb-3 text-center">
          <div id="emailHelp" className="form-text center my-3">
            Didn't have an account ?
          </div>
          <div className="d-grid gap-2 my-3 col-6 mx-auto">
            <button onClick=goToSignUp className="btn btn-success ">
              SignUp Here !
            </button>
          </div>
        </div>
        </form>
      </div>
    </div>
  </div>
</>
);
;

export default LoginPage;

这是handleSUbmit()函数第一行的ss显示错误。

还有我的 API 响应-


    "success": true,
    "authToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoiNjFiMzZlNGVmYTI5MWU1YjdlNWQzZTEwIn0sImlhdCI6MTYzOTI3NDgwMn0.p-Rh_yNe4N-sFZ0G_z7o76FXV9GyFx85xN7A424t9cI",
    "user": 
        "_id": "61b36e4efa291e5b7e5d3e10",
        "name": "Mayank Maroliya",
        "email": "mayank1@test.com",
        "password": "$2a$10$BThh1HeUuhyFBmVc8YzPO.JILhPJsS4sg18sPGe86HmlBjh0svTmi",
        "role": "guest",
        "forgetQues": "Favourite Sport",
        "forgetAns": "Chess",
        "__v": 0
    

我在过去一小时内解决了这个错误,但它没有得到解决。我可以寻求帮助吗?

【问题讨论】:

你可以这样试试> body: email: credentials.email, password: credentials.password, , 我用body: email: credentials.email, password: credentials.password, ,它显示Unexpected token &lt; in JSON at position 0 【参考方案1】:

解决了这个问题,我将email 作为对象传递给onChange 函数。它应该是String

不正确的代码:

setCredentials( ...credentials, [e.target.name]: [e.target.value])

更正的代码:

setCredentials( ...credentials, [e.target.name]: e.target.value)

【讨论】:

以上是关于在 ReactJS 中使用 fetch 时,JSON 中位于位置 0 的意外令牌 I的主要内容,如果未能解决你的问题,请参考以下文章

使用 ReactJS 和 fetch-api 访问和显示 JSON 时遇到问题

在 ReactJS 中使用 fetch 上传状态错误

ReactJS 从 API fetch 中获取令牌字符串

addEventListener('fetch', callback) 在 ReactJS 中永远不会触发回调

类型错误:在 reactjs 中使用 fetch 读取 json 时未定义项目

REACTJS 使用 fetch 通过 const 传递变量