Require 在 NodeJS 应用程序中无法识别

Require is not recognised in NodeJS application

我已按照此处的步骤进行操作 http://expressjs.com/en/starter/installing.html to install express NodeJS application. After installing we moved to "myapp" directory and then we have installed "aws-iot-device-sdk" from https://github.com/aws/aws-iot-device-sdk-js

此处在 node_modules 目录中创建了 aws-iot-device-sdk 目录。

在 public 目录中,我们通过创建 "index.html" 开始探索示例。在浏览器中启动 NodeJS 服务器后,我们尝试打开 http://localhost:3000,此处 index.html 屏幕已打开。

index.html - 我们需要 "aws-iot-device-sdk" 到 运行 AWS - IOT 应用程序的脚本标签,但我们在这里遇到以下错误。

Uncaught ReferenceError: require is not defined

下面是index.html文件

的代码
<!DOCTYPE html>
<html>
<script>
function clicked(){
var awsIot = require('aws-iot-device-sdk');
    }
</script>
<body>
<input type="submit" onclick="clicked()" value="Click here to send email">
</body>
</html>

重定向到 index.html 我们在 app.js

中使用了以下代码
app.use(express.static('public'));

请帮我解决这个问题。

谢谢, 拉凯什·卡尔瓦。

aws-iot-device-sdk 模块设计为 运行 通过节点。

Node 有一个内置的 require 方法,但这在浏览器中本机不可用(这就是错误显示 'require is not defined' 的原因)。

为了 require 客户端代码中的模型,您需要使用模块加载器,例如 require.js

虽然在这种情况下,aws-iot-device-sdk 模块依赖性意味着它将 运行 通过节点。

根据您想要实现的目标,您可能希望在节点中实现一个可以与 AWS 模块一起使用的 API,并从您的 client-side 代码中调用它。

经过长时间的研究,我通过将 "ejs" 添加到 NodeJS 应用程序中解决了这个问题。现在我可以在浏览器中调用 Require 了。

现在我们可以从浏览器访问AWS-IOT。