【问题标题】:How can I prevent res.send() from overwriting the entire document? [duplicate]如何防止 res.send() 覆盖整个文档? [复制]
【发布时间】:2022-01-16 13:19:01
【问题描述】:

我正在触发一个处理将用户插入数据库的 ajax 调用。

我想给ajax成功返回一个字符串或者状态码以供进一步使用。

如果我使用 res.send() 服务器端,它会覆盖当前文档并在黑色文档的左上角显示响应。

我尝试使用 return,但也没有用,除非我做错了什么。

客户端

$.ajax({
    url: "/register",
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify({ data: data }),
    success: function (response) {
      console.log(response);  
      Swal.fire({
        title: "Success!",
        text: "All good",
        icon: "success",
      });
    },
    error: function (e) {
      Swal.fire({
        title: "Error!",
        text: "There was an error saving to the database",
        icon: "error",
      });
      console.log(e);
    },
  });

服务器端

router.post("/", async (req, res) => {
  req.body = sanitize(req.body);

  const user = new User({
    username: req.body.username,
    email: req.body.email,
    password: req.body.password,
  });

  try {
    await user.save();
    res.status(200).send("Success");
  } catch (e) {
    res.status(500).send("Error");
    // Implement response to the user if for some reason the save failed
  }
});

【问题讨论】:

  • 这个 ajax 是在表单提交中完成的吗?这些症状对于 ajax 请求没有意义。显示的路线也没有send()
  • 抱歉,这是我尝试的最新方法。我将问题更新为我最初尝试的内容。是的,提交按钮调用一个 js 函数,该函数执行一些输入验证并提交文档。
  • 所以问题很可能是您没有阻止默认表单提交并且页面正在重新加载。向我们展示提交代码,您能确认页面重新加载吗?

标签: javascript ajax express


【解决方案1】:

我将 ajax 调用包装在一个我没有在任何地方调用的函数中,我只是在默认情况下执行常规表单提交。关闭

【讨论】:

    猜你喜欢
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2012-11-20
    相关资源
    最近更新 更多