在 javascript-nodejs 中的 .then() 块内使用 async-await 块时出现问题

2024-04-16

Problem:
我使用 ipManager 作为中间件。但由于某种原因,同一个 json 对象被添加到 firestore 两次。此外,许多其他线路也在重复。

Code:

//imports...
exports.ipManager = (req, res, next) => {
  const ip = req.clientIp;
  const fullUrl = req.protocol + "://" + req.get("host") + req.originalUrl;
  console.log(fullUrl)
  if ((ip == "::1") & req.get("host").includes("localhost")) {
    console.log(
      "[+] ipManager functionalities restricted due to server running in local machine"
    );
    console.info(`[+] method=GET path=${fullUrl}`);
    next();
    return;
  }
  const _URL = req.originalUrl
  if (_URL.includes("documentation") || _URL.includes("weather") || _URL=="/") {
    console.log(_URL)
  } else {
    next()
    return
  }

  console.log("IP address " + ip);
  axios
    .get(`http://ip-api.com/json/${ip}`)

    // Show response data
    .then((res) => {
      const info = res.data;
      console.info(JSON.stringify(res.data));
      (async () => {
        try {
          const docRef = await addDoc(collection(db, "req_info_2022.1.22"), {
            country: info.country,
            countryCode: info.countryCode,
            region: info.region,
            regionName: info.regionName,
            city: info.city,
            zip: info.zip,
            lat: info.lat,
            lon: info.lon,
            timezone: info.timezone,
            isp: info.isp,
            org: info.org,
            as: info.as,
            ip: info.query,
            path: fullUrl,
          });
          console.log("Document written with ID: ", docRef.id);
        } catch (e) {
          console.error("Error adding document: ", e);
        }
      })()
    })
    .catch((err) => console.log(err));

  next();
};

This is the console log statements:
Note: Observe that the console.logs are getting repeated two times. Due to this, two documents(which are same) are getting saved in the firebase collection. application logs

Forec HTTPS 中间件

'use strict';
exports.redirectToHTTPS = (req,res,next) => {
  var schema = (req.headers['x-forwarded-proto'] || '').toLowerCase();
  if (req.headers.host.indexOf('localhost')<0 && schema!=='https') {
    res.redirect('https://' + req.headers.host + req.url);
  } else {
    next();
  }
}

您的代码有很多问题,但是使用 async/await 而不是 Promise 链和 IIFE,将使调试变得更容易。

//imports...
exports.ipManager = async (req, res, next) => {
  const ip = req.clientIp;
  const fullUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
  const isLocalMachineCalling =
    (ip == "::1") && req.get("host").includes("localhost");

  if (isLocalMachineCalling) {
    console.log(
      "[+] ipManager functionalities restricted due to server running in local machine"
    );
    console.info(`[+] method=GET path=${fullUrl}`);
    next();
    return;
  }
  if (["documentation", "weather", "/"].includes(req.originalUrl)) {
    console.log(req.originalUrl);
  } else {
    next();
    return;
  }

  console.log("IP address " + ip);
  const results = await axios.get(`http://ip-api.com/json/${ip}`);
  const info = results.data;

  try {
    const docRef = await addDoc(collection(db, "req_info_2022.1.22"), {
      country: info.country,
      countryCode: info.countryCode,
      region: info.region,
      regionName: info.regionName,
      city: info.city,
      zip: info.zip,
      lat: info.lat,
      lon: info.lon,
      timezone: info.timezone,
      isp: info.isp,
      org: info.org,
      as: info.as,
      ip: info.query,
      path: fullUrl,
    });
    console.log("Document written with ID: ", docRef.id);
  } catch (e) {
    console.error("Error adding document: ", e);
  }

  next();
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 javascript-nodejs 中的 .then() 块内使用 async-await 块时出现问题 的相关文章

随机推荐

  • 使用小数分隔符和千位分隔符验证小数

    您好 我使用这个正则表达式来验证带有小数分隔符和千位分隔符的数字 ets eds 0 9 ets eds 0 9 但是这个fail 它不应该接受 对于我的两个单元测试用例 12 and 1 2 有人可以帮忙吗 注意 这项工作适用于1 2 让
  • 如何使用node.js驱动程序复制mongodb集合?

    有没有办法通过 Node js mongodb 驱动程序复制集合 i e collection copyTo duplicate collection 您可以评估copyTo 服务器端虽然它会阻止整个 mongod 进程并且不会在新集合上创
  • 中小型 .NET 应用程序的数据库(和 ORM)选择

    我需要开发一个基于 NET 的应用程序 其数据需求可能超过 SQL 2005 Express Edition 的 4 gig 限制 由于内部 DBA 的专业知识 同一应用程序的其他客户 将来 可能需要使用特定的数据库平台 例如 Oracle
  • 在 Rails 表单错误消息中显示链接

    在我们的注册表单上 我们validates uniqueness of email 当用户尝试使用我们的注册表单并指定现有的电子邮件地址时 我希望他们看到这样的错误消息 该邮件地址已被使用 如果您在登录时遇到问题 您可以重置你的密码 htt
  • 如何计算闰年?

    我对闰年有一些疑问 如何通过使用这样的公式来确定 add years function x y if isTRUE all equal y round y stop Argument y must be an integer n x lt
  • UIImageview 以快速编程方式

    我只是想创建一个UIImage以编程方式查看 我有一个新视图 我尝试这样做 let imageName yourImage png view backgroundColor UIColor colorWithPatternImage UII
  • 如何使用maven pom.xml创建jar

    我需要一个示例 pom 文件来为我的 spring 项目创建 jar 文件 创建jar文件时如何指定创建资源的目录和文件夹 我可以使用 pom jar 文件创建 jar 文件 但我需要将 applicationContext xml 包含在
  • 在 PHP 中使用 pthreads 创建异步超时

    我正在尝试在 PHP 中创建某种异步超时 我使用 PECL 扩展 pthreads 来实现多线程 异步超时工作正常 但参考却不然 我使用 PHP 5 5 8 进行此测试 class ParentClass public test publi
  • tensorflow conv2d偶数步长和奇数步长之间的不同起始索引

    据我了解从tf nn conv2d 文档 https www tensorflow org api docs python tf nn conv2d对于相同的卷积 无论步幅如何 第一个点积应以 0 0 为中心 正如您在下面看到的 当步幅为奇
  • 如何从 boost::shared_ptr 释放指针?

    boost shared ptr 可以释放存储的指针而不删除它吗 我可以看到文档中不存在释放函数 并且在常见问题解答中也解释了为什么它不提供释放函数 例如不能在不唯一的指针上完成释放 我的指点是独一无二的 我怎样才能释放我的指针 或者使用哪
  • 我应该为 SCJP 准备多长时间? [关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 好吧 我知道这可能听起来有点傻 因为这取决于个人 但平均来说我应该花多少时间来准备 SCJP 我已经有一些 Java 经验 我的大学的一些中小型项目
  • 导入XML - JavaScript?导入的内容为空[重复]

    这个问题在这里已经有答案了 我正在尝试导入一个字段 该字段有助于指示餐厅当前是否接受在线订单 INDEX IMPORTXML https www doordash com store yolk test kitchen chicago 39
  • 保存并加载 keras 自动编码器

    看看这个奇怪的加载 保存模型情况 我保存了变分自动编码器模型及其编码器和解码器 autoencoder save autoencoder save overwrite True encoder save encoder save overw
  • 想要下载Git仓库,我需要什么(windows机器)?

    我想下载这个开源应用程序 他们正在使用 Git 下载代码库需要什么 Update使用 Git Bash 时如何更改工作目录 我想将存储库下载到某个目录 使用 pwd 告诉我我将在不需要的地方下载存储库 下载Msys 上的 Git http
  • 如何重定向 python 中函数的打印输出[重复]

    这个问题在这里已经有答案了 可能的重复 我可以将 python 中的标准输出重定向到某种字符串缓冲区吗 https stackoverflow com questions 1218933 can i redirect the stdout
  • 当模型以编程方式更改时调用 ngChange

    当以编程方式更改模型时调用 Angular 的 ng change 时 我遇到问题 scope sendMessage function scope message Message sent scope confirmed true sco
  • 帮助使用 GPS 坐标,Android

    我正在使用此代码来获取我的位置并在屏幕上打印坐标 package com example alpha import android app Activity import android content Context import and
  • 如何使用 DynamicResource 更新 SolidColorBrush 颜色?

    我正在尝试动态更改画笔的颜色 我写了一个非常简单的例子 但我不明白为什么它不起作用 我在我的应用程序的 ResourceDictionary 中定义了一个前景色和一个使用该颜色作为 DynamicResource 的前景画笔
  • 是否有一个 WPF 控件可以在类似资源管理器的视图中显示文件列表?

    我经常需要向用户显示文件列表 例如作为搜索查询的结果 通常我会描述我自己的简单 DataTemplateFileInfo 但我懒得重新实现资源管理器的所有功能 视图 排序 上下文菜单和拖放 我觉得这个问题很常见 并且有人已经为此目的组装了一
  • 在 javascript-nodejs 中的 .then() 块内使用 async-await 块时出现问题

    Problem 我使用 ipManager 作为中间件 但由于某种原因 同一个 json 对象被添加到 firestore 两次 此外 许多其他线路也在重复 Code imports exports ipManager req res ne