如何轻松地将Node.js的变量传递给视图

时间:2014-11-07 19:54:53

标签: javascript node.js express

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

这是我的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>

有没有办法像这样做?

2 个答案:

答案 0 :(得分:1)

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

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

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

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

答案 1 :(得分:0)

您需要确保使用服务器端模板引擎(快速附带jade支持)。

使用npm将jade安装到您的快递应用程序。然后告诉快递模板的位置,并且,在获取路径定义中,您必须指示表达要使用的视图:

var express = require("express");
var app = express();
// Tell express where your templates are
app.set("views", __dirname + "/views");
// Tell express templates are jade files
app.set("view engine", "jade");
app.get("/", function(req, res) {
  res.render("home", {
    title: "Home Page",
    body: "This is just a test..."
  });
});
app.listen(8080);

完成所有设置后,请创建views/layout.jadeviews/home.jade

Home.jade看起来像这样:

extends layout
block content
  h1= title
  p A tag name followed by the equals (=) sign is like php echo
  p= body
  ul
    li This is a hardcoded list
    li With two elements

Layout.jade将如下所示:

html
  head
    meta(charset="utf-8")
    title= title
    link(rel="stylesheet", href="/css/main.css")
    meta(name="viewport", content="width=device-width")
  body

    block content
      div.page-content.text-center
        h1 Default content
        p anything I put here will be overridden by the home.jade content block Which means that any jade view that doesn't provide a `block content` part will render this text instead.

如果您创建另一条路线,例如:

app.get("/default", function(req, res) {
  res.render("test", {title: "Default route", body: "Whatever"});
});

然后是相应的模板views/test.jade

extends layout
  p I'm not providing a `block content` so this text won't be rendered
  blockquote(class="my-class", id="my-id") In jade, the very first word of a line is the tag to be used by the line, to provide attributes to a tag you use comma-separated HTML attributes in between parenthesis right next to the tag name.

并在http://localhost:8080/default访问您的路线您将看到要呈现的默认文字。


我希望这有帮助。