【问题标题】:How to get multiple APIs request into a single page without using promise package如何在不使用 Promise 包的情况下将多个 API 请求放入单个页面
【发布时间】:2021-03-31 19:09:48
【问题描述】:

我正在尝试使用 Nodejs 将 2 个 API 放入一个页面。我已经搜索过相同的内容,但它说要使用 promise 包,但现在已弃用,请帮助我


app.post("/", function (req, res) {
  const username = req.body.username;

  const url1 = "https://codeforces.com/api/user.info?handles=" + username;

  https.get(url1, function (response) {

    response.on("data", function (data) {

      const code = JSON.parse(data);

      res.render("result", { id: username, rating: code.result[0].rating, rank: code.result[0].rank, freinds: code.result[0].friendOfCount, contri: code.result[0].contribution });
    });
  })
  const url2 = "https://codeforces.com/api/user.status?handle=" + username;

  https.get(url2, function (response) {

    response.on("data", function (data) {

      const code = JSON.parse(data);

      res.render("result", { cid: code.result[0].contestId });

    })
  })
})

【问题讨论】:

  • 哪个包被弃用了?

标签: node.js express ejs


【解决方案1】:

简单的方法 - 在回调中使用回调:当第一个请求完成时,启动第二个请求,当第二个请求完成时,让调用 render 来自第一个请求和第二个请求的响应。

app.post("/", function (req, res) {
  const username = req.body.username;

  const url1 = "https://codeforces.com/api/user.info?handles=" + username;
  https.get(url1, function (response) {
    response.on("data", function (data) {
      const code1 = JSON.parse(data);

      const url2 = "https://codeforces.com/api/user.status?handle=" + username;
      https.get(url2, function (response) {
        response.on("data", function (data) {
          const code2 = JSON.parse(data);

          res.render("result", {
            id: username,
            rating: code1.result[0].rating,
            rank: code1.result[0].rank,
            freinds: code1.result[0].friendOfCount,
            contri: code1.result[0].contribution,
            cid: code2.result[0].contestId
          });
        });
      });
    });
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多