我需要在单击按钮后将 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)
})
所以我在文件“投票”(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 变量)重置为初始状态? 我只是在做原型(prototype)设计,所以一种快速而肮脏的方法可能会奏效。
最佳答案
我建议构建或使用某种用户验证,并且每个用户都有一份只属于他的初始数据副本。请记住,这些数据永远不会被垃圾收集,因此您必须自己管理删除。我使用了 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)
});
关于javascript - 如何在nodejs中重置json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56810544/