首页 > 解决方案 > 使用节点 js 的 ajax 响应

问题描述

我无法在 ajax 中得到响应。我知道我走的是正确的路线,因为它正在响应后端的正确日志。但我无法得到 res.end 工作。我尝试了其他方法以及来自这篇文章的示例。如何从 Node.js 中的 ajax 帖子返回成功

    $.ajax({
      url: "/register",
      method: "POST",
      async: false,
      dataType: "json",
      data: { email: email, type: "checkCount" },
      success: function (result) {
        console.log(result.status + " status of result"); // does not display result...
      },
      error: function (xhr, status, error) {
        var errorMessage = xhr.status + ": " + xhr.statusText;
        console.log(errorMessage);
      },
    });

////////////////////////////////////////////////////////////

var express = require("express");
var router = express.Router();
var postFunctions = require("../public/postFunctions/register");

router
  .route("/")
  .get(function (req, res) {
    res.render("register");
  })
  //@param dm = decisionMaker for post -- dm = req.body.type -- type in switch -- response made
  .post(function (req, res) {
    let dm = req.body.type;
    switch (dm) {
      case "registerForm":
        res.send("uploadData");
        break;
      case "checkCount":
        console.log("should be an error message"); // this displays fine so i know route works
        res.end('{"success" : "Updated Successfully", "status" : 200}'); //not sure why not showing in ajax result
        break;
      default:
        res.send("action failed. type not found");
    }
  });

module.exports = router;

标签: javascriptnode.jsajax

解决方案


它应该是 res.send 你已经使用了 res.end 。请使用正确的语法。res.end() 将结束响应过程。


推荐阅读