簡體   English   中英

使用node.js寫入文件后無法訪問此站點的本地主機

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM