gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:29:02 26 4
gpt4 key购买 nike

我正在尝试学习 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com