最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Postman hangs (keeps loading) on sending a request to an express route - Stack Overflow

programmeradmin2浏览0评论

I created this api that generates a connection request between two user (similar to linkedin or any other social media)

/**
 * 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);
        }
      });
  });
};

Here I am first checking if provided userids are valid of not. I am using a model User that provides me facility to check if user exists with userid by findByUsername() function.

I checked each model individually, the are working. But On sending request on above route, postman keeps on loading. Please let me know solution.

Find by username model:

/**
 * 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]);
    });
  });
};

Connects constructor:

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

Method for creating connect:

/**
 * 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);
    });
  });
};

THIS IS ROUTE:

// 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));
    }
  }
);

POSTMAN BEHAVIOUR:

I created this api that generates a connection request between two user (similar to linkedin or any other social media)

/**
 * 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);
        }
      });
  });
};

Here I am first checking if provided userids are valid of not. I am using a model User that provides me facility to check if user exists with userid by findByUsername() function.

I checked each model individually, the are working. But On sending request on above route, postman keeps on loading. Please let me know solution.

Find by username model:

/**
 * 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]);
    });
  });
};

Connects constructor:

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

Method for creating connect:

/**
 * 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);
    });
  });
};

THIS IS ROUTE:

// 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));
    }
  }
);

POSTMAN BEHAVIOUR:

Share Improve this question edited Sep 7, 2020 at 13:29 Shubham Singh asked Sep 7, 2020 at 13:07 Shubham SinghShubham Singh 1101 gold badge2 silver badges8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

You didn't show us the Express route handler for your API. It seems from your Postman hang that your route handler never calls anything like

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

after all your promises are resolved. Postman's patiently waiting for a response from your node express server, or a timeout.

ISSUE FIXED:
This is so embarrassing to say but yeah, I made that mistake.
In the sendRequest method, I defined constant variables userId and friendId, and I am modifying it like userId = data.id.
I changed constant variables to local variables using the let keyword.

CHANGED:
FROM:

const userId = 0;
const friendId = 0;

TO:

let userId = 0;
let friendId = 0;  

But, I want an explanation of why I didn't get an error at the console when I tried changing constant variable? Did this things happens with Promises?

发布评论

评论列表(0)

  1. 暂无评论