首页 > 解决方案 > 如何在nodejs中重置json文件

问题描述

单击按钮后,我需要将 json 文件重置为原始状态。目前,我正在使用路由器建模,我需要帮助来扩展我现有的代码。

这是我在 server.js 文件上编写的代码片段,我运行“nodemon”来启动服务器。

var messages = [{index:0, rating:0}, {index:1, rating:0}]
app.get('/votes', (req, res) =>{
    res.send( messages )
})

app.post('/votes', (req, res) =>{
    votes.push(votes)
    res.sendStatus(200)
})

所以我对文件'votes'(json格式)的初始状态是:

[{"index":0,"rating":0}, {"index":1, "rating":0}]

在一些用户操作之后,我将使用以下代码将一些数据添加到这个 json 文件中:

<body>
// some logic here
    <script>
        $(() => {
            $("#submit").click(()=>{
                var message = [ { index:1, rating: $("#input").val()},
                                { index:2, rating: $("#input2").val()}]
                postMessage(message)
            })
        })
        function postMessage(message) {
            $.post('http://localhost:8080/votes', message)
        }
   </script>
</body>

然后我的json文件中有以下内容

[{"index":0,"rating":0}, {"index":1, "rating":0}, {"index":1, "rating":1}, {"index":2, "rating":3}]

问题:如何通过单击按钮进行新事务将 json 文件(不是 json 变量)重置为初始状态?我只是在做原型设计,所以一种快速而肮脏的方式可能会奏效。

标签: javascriptnode.jsjson

解决方案


我建议构建或使用某种用户验证,并且每个用户都有一份初始数据的副本。请记住,这些数据永远不会被垃圾收集,因此您必须自己管理删除。我使用了 express 提供的基本 IP,但这不是一个好习惯。使用npm-memorystore这将为您提供一些内存管理。如果你想识别用户,你可以使用express-sessionexpress-jwt

var messages = [{
    index: 0,
    rating: 0
}, {
    index: 1,
    rating: 0
}];
var usersMessages = {};

app.get('/votes', (req, res) => {
    var userIp = req.ip;
    usersMessages[userIp] = [].concat(messages);
    res.send(usersMessages[userIp]);
});

app.post('/votes', (req, res) => {
    var userIp = req.ip;
    var userVotes = usersMessages[userIp];
    if (!userVotes)
        usersMessages[userIp] = [].concat(messages);
    usersMessages[userIp].push(req.body.votes);

    res.sendStatus(200)
});


推荐阅读