javascript - 如何在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 变量)重置为初始状态?我只是在做原型设计,所以一种快速而肮脏的方式可能会奏效。
解决方案
我建议构建或使用某种用户验证,并且每个用户都有一份初始数据的副本。请记住,这些数据永远不会被垃圾收集,因此您必须自己管理删除。我使用了 express 提供的基本 IP,但这不是一个好习惯。使用npm-memorystore这将为您提供一些内存管理。如果你想识别用户,你可以使用express-session,express-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)
});
推荐阅读
- jpa - 我可以用一个persistance.xml 配置文件创建几个JPA 'peresistance-unit' 吗?
- rust - 仅当存在 println!() 时隐式类型才会产生编译器错误
- java - 在应用程序启动时通过 api 调用设置属性值
- ftps - SecureBlackBox:FTPS:Implicit - 建立 SSL/TLS 数据连接时出错
- php - 在 Laravel 刀片中显示两个具有相同名称的连接字段的问题
- html - Rails 动态提供 VTT 内容
- scheme - 为什么这个简单的方案代码会出错?
- javascript - 在数组对象内找到未定义并插入对象
- python - Pandas:有效的正则表达式似乎不适用于数据帧上的 str.extract
- python - 如何使用python3拆分包含字符串的嵌套列表