【问题标题】:Postman hangs (keeps loading) on sending a request to an express route邮递员在向特快路线发送请求时挂起(继续加载)
【发布时间】:2020-12-25 21:57:02
【问题描述】:

我创建了这个 api 来生成两个用户之间的连接请求(类似于linkedin 或任何其他社交媒体)

/**
 * sendRequest
 * * Send request to a user
 * TODO: Testing required
 * @param {string} from username of request send from
 * @param {string} to username of request send to
 */
User.sendRequest = (from, to) => {
  return new Promise((resolve, reject) => {
    const userId = 0;
    const friendId = 0;

    User.findByUsername(from)
      .then((data) => {
        userId = data.id;
        console.log(data);
        User.findByUsername(to)
          .then((data) => {
            friendId = data.id;
            Connects.checkConnectionStatus(from, to)
              .then((areFriends) => {
                if (!areFriends) {
                  const connects = new Connects({ userId, friendId });
                  console.log(connects);
                  Connects.create(connects)
                    .then((data) => resolve(data))
                    .catch((err) => reject(err));
                } else {
                  const newError = new Error(
                    `Users ${from} and ${to} are already connections`
                  );
                  newError.status = 400;
                  return reject(newError);
                }
              })
              .catch((err) => {
                console.log(`Error: ${err}`);
                return reject(err);
              });
          })
          .catch((err) => {
            if (err.status && err.status === 404) {
              reject(err);
            }
          });
      })
      .catch((err) => {
        if (err.status && err.status === 404) {
          reject(err);
        }
      });
  });
};

在这里,我首先检查提供的用户 ID 是否有效。 我正在使用一个模型用户,它为我提供了通过 findByUsername() 函数检查用户是否存在用户 ID 的工具。

我分别检查了每个模型,它们都在工作。但是在上述路线上发送请求时,邮递员继续加载。请告诉我解决方案。

按用户名型号查找:

/**
 * findByUsername
 * * Finds a user by username
 * @param {string} username username whose detail needed to find
 */
User.findByUsername = (username) => {
  return new Promise((resolve, reject) => {
    const query = `
            SELECT 
                u.*, p.* 
            FROM user u INNER JOIN profile p 
            ON u.username = p.username 
            WHERE u.username = ?
        `;
    sql.query(query, username, (err, res) => {
      if (err) {
        console.log(`Error: ${err}`);
        return reject(err);
      }
      if (!res.length) {
        const newError = new Error(`User with username ${username} not found`);
        newError.status = 404;
        return reject(newError);
      }
      console.log(`Found user: `, res);
      resolve(res[0]);
    });
  });
};

连接构造函数:

// constructor
const Connects = function (connect) {
  this.userId = connect.userId;
  this.friendId = connect.friendId;
  this.status = 1;
};

创建连接的方法:

/**
 * create
 * * Creates a new connection request between two users
 * @param {object} newConnect A connection object
 */
Connects.create = (newConnect) => {
  console.log(newConnect);
  return new Promise((resolve, reject) => {
    const query = "INSERT INTO connects SET ?";
    sql.query(query, newConnect, (err, res) => {
      if (err) {
        console.log(`Error: ${err}`);
        return reject(err);
      }
      const response = { id: res.insertId, ...newConnect };
      console.log(`Created connect: `, response);
      resolve(response);
    });
  });
};

这是路线:

// TODO: Send request
router.post(
  "/request",
  [body("from").not().isEmpty().escape(), body("to").not().isEmpty().escape()],
  (req, res, next) => {
    // Finds validation errors and return error object
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    const { from, to } = req.body;

    if (from === to) {
      const newError = new Error("Equal input is not allowed");
      newError.status = 400;
      next(newError);
    } else {
      User.sendRequest(from, to)
        .then((data) => res.json(data))
        .catch((err) => next(err));
    }
  }
);

邮递员行为:

【问题讨论】:

    标签: javascript mysql node.js express postman


    【解决方案1】:

    您没有向我们展示您的 API 的 Express 路由处理程序。从您的 Postman 挂起看来,您的路由处理程序从不调用类似的东西

    res.json(whatever).status(200).end()
    

    在你所有的承诺都得到解决之后。邮递员正在耐心等待您的节点快递服务器的响应,或者超时。

    【讨论】:

    • 我也加了路线,请查收。
    • 您可能应该使用调试器或 console.log 行,以确保您的 res.json() 行实际上在您的服务器中运行。我不认为是。
    • 是的,我正在使用控制台日志。实际发生的是第一个 id (from),控制台正在打印响应,但之后它就没有继续了
    【解决方案2】:

    问题已修复:
    说起来很尴尬,但是是的,我犯了那个错误。
    在 sendRequest 方法中,我定义了常量变量 userId 和friendId,我将其修改为 userId = data.id。
    我使用 let 关键字将常量变量更改为局部变量。

    更改:
    来自:

    const userId = 0;
    const friendId = 0;
    

    到:

    let userId = 0;
    let friendId = 0;  
    

    但是,我想解释一下为什么当我尝试更改常量变量时​​控制台没有出现错误? Promises 是否发生过这种情况?

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 2019-05-12
      • 2021-09-04
      • 2020-07-29
      • 2022-01-23
      • 2019-07-26
      • 1970-01-01
      • 2020-11-16
      • 2020-12-11
      相关资源
      最近更新 更多