1

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

course is defined, I just didn't include all of my code to narrow down where the problem is.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.