javascript - 如何使用 Node.js 轻松地将变量传递到 View

标签 javascript node.js express

我正在尝试学习 Node.js 的基础知识,但如果不使用 Jade 或其他模板引擎,我似乎无法简单地将变量从 app.js 发送到 index.html。

这是我的 app.js

var express = require("express");
var app = express();
app.get('/', function(req, res){

    //I'd like to send this as a variable instead    
    res.send("some text");

});
app.listen(8080);

这是我的index.html

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        //I want to alert my variable here please
        alert(variableFromAppjs);
    </script>
</head>
<body>
    <p>Hello</p>
</body>
</html>

有没有办法简单地做到这一点?

最佳答案

您不能只是将变量从 app.js“发送”到 index.html 的原因是因为它们是两个独立的程序。 index.html 仅通过浏览器在客户端计算机上运行,​​app.js 仅在服务器上运行。

为了让index.html从app.js接收数据,您需要使用XMLHttpRequest向您的Node应用程序发出请求。

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

然后您可以异步接收数据并将其保存到您想要的任何变量中。

关于javascript - 如何使用 Node.js 轻松地将变量传递到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26809082/

相关文章:

javascript - 如何在 GatsbyJS 节点中添加自定义 GraphQL 参数?

javascript - Google 日历 API 空闲/忙碌 : query does not retun events separatly

node.js - 如何使用 MongoDB Geospatial 选择查询中的字段?

ajax - Node js无法解析字符串化的json

javascript - Chart.js - 如何将标签值显示为 X 和 Y 值的百分比 - 目前始终为 100%

javascript - 如何打开带有数据url图像的新页面?

javascript - 找不到\node_modules\@tensorflow\tfjs-node\lib\napi-v4\tfjs_binding.node

node.js - NodeJS 等待所有异步命令完成

node.js - 无法从函数中获取输出

node.js - 如何使用 Express + Docker + Azure 映射端口