通过使用Ajax调用将数据从NodeJS发送到客户端

我通过运行Ajax调用在服务器上增加一个值,并在完成后更新我的UI

function increaseHitpoints(){ $.ajax({ type: 'GET', url: 'http://localhost:8888/incHp/2312' }).done(function (data) { $("#txtHitpoints").html(data); }); } 

在我的app.js中,我读了一个JSON文件,操纵这个值,把它写回到这个文件并且把它返回给客户端

 app.get('/incHp/:id', function (req, res) { var database = './database.json'; fs.readFile(database, 'utf8', function (err, data) { // read the data var json = JSON.parse(data); var users = json.users; var hitpoints; users.find(u => { if (u.id === Number(req.params.id)) { // get the user by id u.hitpoints++; hitpoints = u.hitpoints; } }); json = JSON.stringify(json); fs.writeFile(database, json, (err) => { // update the JSON file // -> missing part here <- }); }); }); 

如果我想要返回新的值,我有什么要进入缺less的部分? 新的价值将是hitpoints

我尝试了res.send(hitpoints); 但似乎这个函数想要返回一个状态码,而不是一个值。

如果您发送数字值,则会将其视为HTTP响应代码https://expressjs.com/en/api.html#res

但是你可以发送你的hitpoints作为一个stringres.send(hitpoints.toString())或者json res.send({hits: hitpoints});

取决于你想要什么样的格式。 我更喜欢使用JSON。 所以在JSON的情况下,你会这样做:

 fs.writeFile(database, json, (err) => { res.status(200).json({yourKey: yourValue}); }); 

然后你可以访问前端的JSON对象:

 $("#txtHitpoints").html(data.yourKey);