I am pretty new to JS so please go easy on me.
Im trying to increment a value in a JSON file in my JS backend application. Whenever I increment the associated value by the key, it creates a new section "undefined"
Here is the entire application:
const { response } = require("express");
const express = require("express");
const fs = require("fs").promises;
const path = require("path");
const app = express();
const dataFile = path.join(__dirname, "data.json");
//support POSTing form data wuth url encoded
app.use(express.json());
app.get("/poll", async (req, res) =>{
//data is now the js object of the Json data json
let data = JSON.parse(await fs.readFile(dataFile, "utf-8"));
const totalVotes = Object.values(data).reduce((total, n) => total =n, 0);
data = Object.entries(data).map(([label, votes]) => {
return{
label,
percentage: (((100 * votes) / totalVotes) || 0).toFixed(0) // or with 0 in the even that you divide by zero
}
});
res.json(data);
});
app.use(express.urlencoded({ extended: true}));
app.post("/poll", async (req, res) => {
const data = JSON.parse(await fs.readFile(dataFile, "utf-8"));
data[req.body.add] ;
await fs.writeFile(dataFile, JSON.stringify(data));
res.json(data);
});
app.listen(3000, () => console.log("Server is running ..."));
Here is my JSON file before I POST
{
"JavaScript":0,
"TypScript":10,
"Both":3}
Here is a picture of my POST request in Insomnia:
Here is my JSON file after a Post Requests
{
"JavaScript": 0,
"TypScript": 10,
"Both": 3,
"undefined": null
}
Here is is after a second POST request:
{
"JavaScript": 0,
"TypScript": 10,
"Both": 3,
"undefined": 1
}
I know it might be something very simple, but I am very inexperienced so any help would be greatly appreciated!
I tried including some additional middleware to enable bodyParsing as I saw in other posts but that did not fix the issue.
I also tried
console.logging(req.body)
,but that only printed "undefined".
EDIT: I found the problem, I wasn't sending the information in Insomnia correctly, I need to click the form type and either format a JSON input or select the "Form URL Encoded"" Option. Otherwise it doesn't recognize the format.
Thank you for your help!
CodePudding user response:
I tried your code in my device, it works fine on my device which means you are not properly sending post request.
And there is a bug in your logic of adding name , in which you increament the add
property of data
object but that property is not a number but a null so the number does not increments. Here is a simple fix...
app.post("/poll", async (req, res) => {
const data = JSON.parse(await fs.readFile(dataFile, "utf-8"));
let {add} = req.body;
if(data[add] === 0 || data[add]) data[add] ;
else data[add] = 0;
await fs.writeFile(dataFile, JSON.stringify(data));
res.json(data);
});
CodePudding user response:
If req.body printed "undefined", req.body.add will also be equal to "undefined". This is causing the error. I haven't used Insomnia but when you send your POST request your "body" needs to be something like this:
`{
"add": "variableName"
}`