Hi,I am trying to send a post request from my frontend and then pushing the same data to an array in my frontend also. The first post request creates a json file in the backend and stores my JSON data inside an array just fine. My issue arrises when i make this first post from the frontend...for some reason it doesnt get pushed into the array. I've stringifed the response data to show this, as you can see its an object rather than held inside an arrayFirst post not returning inside arrayrouter.get('/bodyWeight', ensureAuthenticated, async (req, res, next) => { const userID = req.user._id try { fs.readFile(bodyWeightData, async (err, data) => { if (err || !data) { return console.log('File not found') } else { const fileData = await JSON.parse(data) const thisUserData = fileData.filter((data) => { return data.userID == userID }) res.status(200).json(thisUserData) } }) } catch (err) { res.json('User data not found') } }) router.post('/bodyWeight', ensureAuthenticated, async (req, res, next) => { const userID = req.user._id const userData = { bodyWeight: req.body.weight, bodyFat: req.body.bodyFat, date: req.body.date, userID } try { fs.readFile(bodyWeightData, async (err, data) => { if (err || !data) { fs.writeFile(bodyWeightData, JSON.stringify([userData]), () => { console.log('File created and body stats added') }) return res.json(userData) } const fileData = await JSON.parse(data) fileData.push(userData) fs.writeFile(bodyWeightData, JSON.stringify(fileData), () => { console.log('New body stats added') }) res.json(fileData) }) } catch (err) { console.log(err) } }) I think the issue arises in the backend get request, i cant explain why though. When I load the page it automatically makes a get request to pull existing data from the json file...of which their isn't any data yet and the file won't even exist, I think it's causing an error for the first post submission. That said can anyone suggest why the first post request doesnt return inside of an array but the subsequent ones correctly do?My frontend is here though for reference:const weightData = []; //READ ALL BODY DATA const getBodyData = async () => { const fetchData = await fetch('http://localhost:3000/user/bodyWeight', { method: 'GET', headers: { 'Content-Type': 'application/json' } }) const bodyData = await fetchData.json() weightData.push(bodyData) console.log(weightData) } getBodyData() //CREATE NEW BODY WEIGHT DATA bodyWeightForm.addEventListener('submit', async (e) => { e.preventDefault() const submitData = await fetch('http://localhost:3000/user/bodyWeight', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ weight: bodyWeightInput.value, bodyFat: bodyFatInput.value, date: dateInput.value }) }) const responseData = await submitData.json() weightData.push(responseData) renderBodyWeightSelectBoxData(responseData) }) Any help appreciated.Thanks.
Submitted February 02, 2020 at 12:48PM by NorthernBoysLuvGravy
No comments:
Post a Comment