Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

node.js - How to not duplicate data when using fs.writeFile?

I'm trying to get some data from a simple form and write a JSON file using node JS and FS. I need this:

[{"id":1,"answer1":"C","answer2":"C"},{"id":2,"answer1":"A","answer2":"A"}]

This is the code I wrote:

const express = require("express");
const fs = require('fs');

const app = express();

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
     extended: true
}));

app.get("/", function(req, res) {
     res.sendFile(__dirname + "/form.html")
});

app.post("/", function(req, res) {

     let result1 = req.body.question1;
     let result2 = req.body.question2;

     const dataFile = require("./data.json");
     const userAnswers = {
          id: dataFile.length + 1,
          answer1: result1,
          answer2: result2,
     };

     dataFile.push(userAnswers);


     fs.writeFile("data.json", JSON.stringify(dataFile), 'utf8', function(err) {
          if (err) {
               console.log("An error occured while writing JSON Object to File.");
               return console.log(err);
          }

          console.log("JSON file has been saved.");

     });

     res.sendFile(__dirname + "/form.html");
});


app.listen(3000, function() {
     console.log("The server is running on 3000")
});

It actually works, the JSON file gets created and when I click on the submit button the inputs disappear, then I can continue putting new data.

The problem is that when I refresh the page, the last input gets duplicated in my JSON file. I don't know how to reset it. May someone help me?

question from:https://stackoverflow.com/questions/65660601/how-to-not-duplicate-data-when-using-fs-writefile

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It sounds like your refresh is resubmitting the previous data (some browsers will prompt you before doing that).

You could keep it from doing that by replacing:

res.sendFile(__dirname + "/form.html"); 

in your app.post() handler with this:

res.redirect("/");

The end-user display will still be the same, but a refresh on that page can't resubmit the previous form POST any more. It will just reload the form without any other side effects.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...