【问题标题】:SyntaxError: Unexpected end of JSON input in react/expressSyntaxError:反应/表达中 JSON 输入的意外结束
【发布时间】:2022-02-06 06:32:24
【问题描述】:

疯狂地抓挠我的头,我的“POST”路线工作得很好,我的“PUT”路线的完全相同的代码在浏览器中返回"SyntaxError: Unexpected end of JSON input"。它会更新,但不会通过我的 fetch 请求的 .then() 部分,而是直接进入 catch 块。

在我的 react 应用上获取:

   const updateCourse = async(e) => { 
        e.preventDefault(); 
         const encodedCreds = btoa(
             `${props.creds.emailAddress}:${props.creds.password}`
           );
        
    await fetch('http://localhost:5000/api/courses/' + params.id, {
         method: 'PUT', 
         headers : {
             'Content-Type': 'application/json', 
             Authorization: `Basic ${encodedCreds}`,
         }, 
         body: JSON.stringify(course)
     }).then(res =>  res.json())
     .then((data) => {
         if(data.message) {
           setErrorMessage(data.message.errors)
         }else{
             nav('/course/' + data)
         }
        })
     
     .catch((err) => {
         console.log('error message', err)
     }); 
         

 

快速 API 响应:

    router.put("/api/courses/:id", authUser, async (req, res) => {
  try {
    const findCourse = await courses.findOne({
      where: {
        id: req.params.id,
      },
    });

    if (findCourse) {
      //----IF ITS A VALID COURSE--//
      const updateCourse = await findCourse.update(req.body);
      res.status(204);
      res.json(updateCourse.id)
      
      
    } else {
      res.json({
        message: "Could not find course",
      });
    }
  } catch (err) {
    res.json({
      message: err
    });
    
  }
});

在这里找到完整的代码:https://github.com/ccarver80/React-REST-FS-API

【问题讨论】:

    标签: reactjs express sequelize.js


    【解决方案1】:

    您传递给 JSON.stringify(course) 的变量未定义。

    【讨论】:

    • 课程已定义,我只是没有包含所有代码以缩小问题所在。
    【解决方案2】:

    修好了!我没有意识到我的 API 正在发回 204 状态,即“无内容”,所以我的客户没有看到任何 JSON 技术上需要处理。

    我的客户端中的一个简单的“IF/ELSE”语句解决了这个问题,

     .then((res) => {
             if(res.status === 204) {
                 nav('/course/' + params.id)
             }else {
                return res.json()
             }
         })
    

    【讨论】:

      猜你喜欢
      • 2015-08-05
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 2019-12-27
      相关资源
      最近更新 更多