简体   繁体   中英

localhost this site cant be reached after writing to a file, with node.js

I'm trying to write to a file with node and essentially I have a form with some check boxes and when the form is submitted, the server writes to the file depending on if input a,b, or c is checked.

The file is some json: { a: 0, b: 0, c: 0 } So if input 'a' is checked I would like to add 1 to key a in the json file.

What actually happens is when I submit the form, the page crashes and says 'this site can't be reached', but the file is updated correctly (when I refresh the webpage it loads properly as well).

Here is the code:

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);
}

Edit: Here's the front end code:

<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;
        }
    }

}

Edit:

Here is the poll.json file:

{"a":2,"b":0,"c":0}

Looks like you forgot to send something back to client after processing form. So just replace your //res.redirect(...) with res.status(200).end('Ok')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM