【问题标题】:Express app, multiple POST requests from the client side crashing pageExpress 应用程序,来自客户端崩溃页面的多个 POST 请求
【发布时间】:2022-09-24 11:13:47
【问题描述】:

我有一个待办事项列表应用程序,它会在待办事项列表状态的每次更改时更新 mongodb 数据库中的字符串 - 该字符串在重新加载时被解析以呈现状态。它工作得很好,除非我按顺序快速触发 5 或 6 个状态更改,它会挂起页面。例如,如果我在几秒钟内删除 5 个任务。我认为问题在于处理所有这些发布请求,但也许它在更新 mongodb 方面?有没有办法在某种队列中处理大量的发布请求?

客户端:

function sendData(obj) {
  fetch(\'/jsondata\', {
    method: \'POST\',
    headers: {
      \'Content-Type\': \'application/json\',
    },
    body: JSON.stringify(obj),
  }).catch(function (error) {
    console.log(error);
  });
  console.log(\'db updated\');
}

这是从客户端请求 POST 请求时运行的 mongo 端...如果有帮助:

app.post(\'/jsondata\', function (req, res) {
  updateUserCache(currentUserEmail, JSON.stringify(req.body));
});

async function updateUserCache(email, newState) {
  const foundUser = await user.findOne({
    email: email,
  });
  foundUser.cachedState = newState;
  const newDate = await Date.now();
  foundUser.date = newDate;
  await foundUser.save();
  console.log(\'user cache has been updated\');
}

    标签: javascript node.js mongodb express fetch-api


    【解决方案1】:

    它挂起是因为您永远不会从后端代码发回响应,并且在某些时候浏览器将停止与它建立新的连接。

    因此,请确保正确结束请求:

    app.post('/jsondata', async function (req, res) {
      await updateUserCache(currentUserEmail, JSON.stringify(req.body));
      res.end();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多