![](/img/trans.png)
[英]Writing to a JSON file (Using Node.js to work on a Localhost server)
[英]localhost this site cant be reached after writing to a file, with node.js
我正在尝试使用node写入文件,并且实质上我有一个带有一些复选框的表单,并且在提交表单时,服务器将根据是否选中输入a,b或c来写入文件。
该文件是一些json:{a:0,b:0,c:0}因此,如果选中了输入“ a”,我想在json文件中的a键上添加1。
实际发生的情况是,当我提交表单时,页面崩溃并显示“无法访问此站点”,但文件已正确更新(当我刷新网页时,它也会正确加载)。
这是代码:
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
fs = require('fs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}))
app.post('/vote/new', handleVote);
function handleVote(req,res){
if(req.body.a === 'on'){
choosePollOption(req,res,'a');
}else if(req.body.b === 'on'){
choosePollOption(req,res,'b');
}else if(req.body.c === 'on'){
choosePollOption(req,res,'c');
}
}
function choosePollOption(req,res,topic){
let poll = {};
fs.readFile(__dirname + '/poll.json', 'utf8', function (err, data) {
poll = JSON.parse(data);
poll[topic] += 1;
console.log(poll)
fs.writeFile(__dirname + '/poll.json',JSON.stringify(poll), function (err,data) {
console.log(err);
console.log(data);
// res.redirect('/'); if I uncomment this line the page does not initially crash but if you submit the form again after refreshing the webpage it crashes the second or third time.
})
})
console.log(poll);
}
编辑:这是前端代码:
<form action="/vote/new" method="POST">
<label for="a">a</label><input id="a" name="a" type="checkbox" class="checkbox" onclick="vote(this)"/>
<label for="b">Mac OS</label><input id="b" name="b" type="checkbox" class="checkbox" onclick="vote(this)"/>
<label for="c">c</label><input id="c" name="c" type="checkbox" class="checkbox" onclick="vote(this)"/>
<input type="submit" />
</form>
let vote = (element) => {
let checkboxes = document.getElementsByClassName('checkbox'); // array of all check boxes
for(let i = 0; i <= checkboxes.length -1; i++){
if(checkboxes[i].id !== element.id){
checkboxes[i].checked = false;
}
}
}
编辑:
这是poll.json文件:
{"a":2,"b":0,"c":0}
好像您忘了在处理表格后将某些东西发回给客户。 因此,只需将您//res.redirect(...)
替换为res.status(200).end('Ok')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.