Home > Net >  SyntaxError: Unexpected end of JSON input in react/express
SyntaxError: Unexpected end of JSON input in react/express

Time:02-06

Scratching my head like crazy, my "POST" route works just fine and the same exact code for my "PUT" route is returning a "SyntaxError: Unexpected end of JSON input" in the browser. It WILL update, but its not going thru the .then() parts of my fetch request, and going right to the catch block.

Fetch on my react app:

   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 response in express:

    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
    });
    
  }
});

find the full code here : https://github.com/ccarver80/React-REST-FS-API

CodePudding user response:

The variable you are passing to JSON.stringify(course) is not defined.

CodePudding user response:

Fixed it! I didn't realize my API was sending back a 204 status which is "No content" so my client wasn't seeing any JSON to process technically.

A simple "IF/ELSE" statement in my client fixed this issue,

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