1

我正在使用 node.js 和 Jade,并且我的 public/views 文件夹中有 index.jade,但是当我运行服务器并转到页面时它没有显示,即使一切正常,也没有错误,并且它应该呈现。这是 server.js 中的代码:

console.log("Hello, world!");

var express = require("express")
  , app = express()
  , http = require("http").createServer(app);

app.set("ipaddr", "192.168.0.103");

app.set("port", 8080);

app.set("views", __dirname + "/views");

app.set("view engine", "jade");

app.use(express.static("public", __dirname + "/public"));

app.use(express.bodyParser());

app.get("/", function(request, response) {

  response.send("Server is up and running");

  response.render("index");

});

http.listen(app.get("port"), app.get("ipaddr"), function() {
  console.log("Server up and running. Go to http://" + app.get("ipaddr") + ":" + app.get("port"));


});

这是我的 index.jade:

doctype 5
html
  head
    link(rel='stylesheet', href='http://fonts.googleapis.com/css?family=Open+Sans')
    link(rel='stylesheet', href='/css/style.css')    
    title Super Awesome Chatroom
  body
    h1 Super Awesome Chatroom
    div
      div.inlineBlock
        span Your name:
          input(type="text", value="Anonymous")#name
        br
        form#messageForm
          textarea(rows="4", cols="50", placeholder="Share something!", maxlength=200)#outgoingMessage
          input(type="button", value="Share", disabled=true)#send
      div.inlineBlock.topAligned
        b Participants
        br
        div#participants
    div#messages

一切都应该正常运行,当我转到 xxx.xxx.xxx:8080 时,它只显示“服务器已启动并运行”,但没有显示 index.jade。任何帮助表示赞赏。

4

1 回答 1

2

如我所见,您忘记了包含router中间件。此外,在您的路由处理程序中,您将返回两个响应。如果您只是想呈现索引视图,请删除 response.send():

var express = require("express")
  , app = express()
  , http = require("http").createServer(app);

app.set("ipaddr", "192.168.0.103");

app.set("port", 8080);

app.set("views", __dirname + "/views");

app.set("view engine", "jade");

app.use(express.bodyParser());

app.use(app.router);

app.use(express.static("public", __dirname + "/public"));

app.get("/", function(request, response) {

  response.render("index");

});

http.listen(app.get("port"), app.get("ipaddr"), function() {
  console.log("Server up and running. Go to http://" + app.get("ipaddr") + ":" + app.get("port"));


});

另外,请始终牢记关于 express 的一个非常重要的事实:定义中间件的顺序至关重要!这就是为什么我为了优先考虑移动了static中间件,因为这是处理您在应用程序中定义的路由回调的中间件。routerrouter

于 2013-11-10T14:52:00.353 回答