【问题标题】:React Unexpected end of JSON input onSubmit反应 JSON 输入的意外结束 onSubmit
【发布时间】:2018-12-26 14:27:15
【问题描述】:

我向 api 发送请求,只有当我从 api 接收到数据时,我才使用该数据设置状态,否则我将状态设置为未定义。 但有时这些数据返回为空(那些数据就是这样),所以在这种情况下,我将 setState 设置为未定义。工作正常,除非我没有输入并尝试发送请求,然后我得到“未处理的拒绝(SyntaxError):JSON 输入的意外结束” 由于我每次都将状态设置为未定义,除非我从 api 获取数据,为什么会发生这种情况?

尝试用 try/catch 包装它以查看错误,但它甚至没有启动。然后我检查了拼写错误等。还尝试将整个 if 语句包装到另一个,它只会在从 api 接收到的数据为真时运行,但它没有做任何事情。

getPictureFunc = async event => {

   event.preventDefault();
   //here i grab values from user input in Form.js
   const year = event.target.elements.year.value;
   const month = event.target.elements.month.value;
   const day = event.target.elements.day.value;

   //here i make request call to NASA's API:
   const api_call = await fetch(
  `https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos? 
earth_date=${year}-

${month}-${day}&api_key=${API_KEY}`
    );
    //here i save received data to JSON:
    const receivedDataFromApi = await api_call.json();

    if (year && month && day) {
      console.log(receivedDataFromApi);
      this.setState({
        sol: receivedDataFromApi.photos[0].sol,
        earth_date: receivedDataFromApi.photos[0].earth_date,
        img: receivedDataFromApi.photos[0].img_src,
        error: ""
      });
    } else {
      this.setState({
        sol: undefined,
        earth_date: undefined,
        img: undefined,
        error: "no pics for this day, try another one"
      });
    }
  };

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    Fetch 调用返回 Promise,因此您不一定需要使用 await,而是可以执行以下操作:

    fetch(https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photosearth_date=${year}-${month}-${day}&api_key=${API_KEY}`)
    .then(res => res.json())
    .then(parsedRes => {
        if(year && month && day){
            this.setState({
            sol: parsedRes.photos[0].sol,
            earth_date: parsedRes.photos[0].earth_date,
            img: parsedRes.photos[0].img_src,
            error: ""
            });
        } else {
           this.setState({
           sol: undefined,
           earth_date: undefined,
           img: undefined,
           error: "no pics for this day, try another one"
           }); 
        }
    })
    .catch(err => {
        console.log(err)
    });
    

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      您的问题是,当您的参数为空时,调用不会返回“空数据”,但实际上会失败。你期望它是 JSON。

      所以,您将返回 "Unhandled Rejection (SyntaxError): Unexpected end of JSON input",因为它告诉您您认为这是 JSON(并在其上调用 api_call.json()),但在这种情况下,来自 NASA 服务器的响应不是 JSON。

      【讨论】:

        猜你喜欢
        • 2018-12-31
        • 2020-07-29
        • 1970-01-01
        • 1970-01-01
        • 2020-07-10
        • 2015-08-05
        • 2021-10-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多