Reputation: 25
I am attempting my first weather app and I believe my POST and GET routes haave something wrong with them but I am not sure what. I got a 500 error which is the most general error so I am having trouble debugging.
github: https://github.com/mylaconcepts/Weather-Journal-App
//Client side code
const getData = async (url = '', data = {}) =>{
const req = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
date: data.date,
temp: data.temp,
content: data.content
})
});
try {
const newData = await req.json();
console.log(newData);
return newData
}catch(error) {
console.log("error", error);
}
};
//server side code
app.get('/all', (req, res) => {
res.send(projectData);
})
app.post('/add', (req, res) => {
const newData = {
temp: req.body.temp,
date: req.body.date,
feelings: req.body.feelings
};
projectData.push(newData);
//res.send(newData);
console.log(newData);
})
Error message:
Upvotes: 0
Views: 916
Reputation: 1921
You see that error because you are trying to JSON parse what is looking like an HTML response. Also based on the status 500 it looks like you have an unhandled exception somewhere in your server.
Seeing your source code, you are initializing projectData
as an object, and then trying to do .push()
to it, which is most likely the cause of the server error.
// Setup empty JS object to act as endpoint for all routes
projectData = {};
//...
app.post('/add', (req, res) => {
const newData = {
temp: req.body.temp,
date: req.body.date,
feelings: req.body.feelings
};
// This will throw an exception like "projectData.push is not a function":
projectData.push(newData);
//...
})
To fix it, a solution can be declaring the projectData
properly as an array:
// Setup empty JS object to act as endpoint for all routes
projectData = [];
Upvotes: 2