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