【发布时间】: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