【问题标题】:Node js: fs WriteFile writing data to file twice节点js:fs WriteFile将数据写入文件两次
【发布时间】:2020-07-04 07:40:02
【问题描述】:

后端的 fs.writeFile 代码运行了两次。 数据追加在控制台出现两次,数据在 JSON 文件中写入两次。

知道为什么会这样吗? 非常感谢任何建议。

编辑:这似乎是一个前端问题。 onFavSubmit 正在运行两次...

前端

    constructor (props) {
        super (props) 
            this.state = {
                inputOne: '',
                chosenOne: ['Favourite Movie', 'X'],
                chosenTwo: ['2nd Favourite Movie', 'X'],
                chosenThree: ['3rd Favourite Movie', 'X'],
                movies:[],
            };
            this.onFavSubmit = this.onFavSubmit.bind(this);
            this.onReset = this.onReset.bind(this);
    }
    onFavSubmit = event => {
        const newFav = {
            first: this.state.chosenOne[0],
            second: this.state.chosenTwo[0],
            third: this.state.chosenThree[0]
        }

        if(this.state.chosenOne[1] === 'X' || this.state.chosenTwo[1] === 'X' || this.state.chosenThree[1] === 'X'){
            alert ('Need All 3 Favourite Shows')
            event.preventDefault();
        } else {
            axios.post('http://localhost:8001/fav', {newFav})
            .then(
                alert('Successfully Added'),
                this.onReset()
            )
            .catch(err => console.log(err.response))
        }
    }
<button className="fav__button" type="button" onClick={this.onFavSubmit}>Click Me</button>

后端

const express = require("express");
const favData = require("../data/fav.json")
const fs = require ('fs')
const router = express.Router();

router.get("/", (_, res) => {
    res.json(favData);
  });

router.post("/", (req, res) => {
    const newFirst = req.body.newFav.first;
    const newSecond = req.body.newFav.second;
    const newThird = req.body.newFav.third;

    const newfavData = {
        First: newFirst,
        Second: newSecond,
        Third: newThird,
    };

    fs.readFile('./data/fav.json', 'utf-8', function (err, data){
        var json = JSON.parse(data);
        json.push(newfavData);
        console.log(newfavData)
        fs.writeFile('./data/fav.json', JSON.stringify(json), function(err){
            if (err) throw err;
            console.log('data appended')
            return;
        })
    })

});

module.exports = router;

【问题讨论】:

  • 请提供上下文,什么代码在调用这段代码?
  • 我包含了我的其余代码
  • 是否还有2个请求,还是只有后端的函数触发了两次?
  • 我猜浏览器可能会尝试预取网站或其他东西,因此端点“/”处的请求被触发两次,fs.readFile 也是如此 - 考虑在单独的端点上移动读取文件。跨度>
  • @Zydnar 如果我正确理解你的问题,我改为 axios.post('localhost:8001/fav/fav', {newFav}) 和 router.post("/fav", (req, res) = > {...} 在后端仍然触发两次...

标签: javascript node.js reactjs fs writefile


【解决方案1】:

我没有足够的声誉,所以我无法发表评论。 您是否尝试过注释掉 this.onReset() 并查看是否可以解决问题?

我曾多次在重新加载时向“/”发送请求。

【讨论】:

  • 同样的问题很遗憾
  • 您可能会触发该事件两次,也许您可​​以包含您将onFavSubmit 附加到某物的代码。
  • 我认为你是对的。 onFavSubmit 运行了两次。虽然不知道我做错了什么
  • 也许您忘记在调用axios.post(...)else 语句中使用event.preventDefault()
猜你喜欢
  • 1970-01-01
  • 2016-03-14
  • 1970-01-01
  • 2011-11-21
  • 1970-01-01
  • 2023-03-23
  • 2023-04-11
  • 1970-01-01
  • 2020-05-18
相关资源
最近更新 更多