2016-06-07 46 views
2

这不是一个问题,关于express.static()如何使用Node.js的

我有一个应用程序,我要为具有相同的JS和CSS依赖多页,包括在HTML静态文件。因此,编写css和js包括在每一页上使用<script><link>标签是不好的做法。

我期待看起来像php包括的方式来做到这一点。由于php会处理所有的php代码并发送编译后的html,我认为可以通过节点服务器上的js来完成。

那么服务器会做有点象下面这样:

  1. 获取HTML从resources.html
  2. 推上面的html的index.html
  3. 发送的index.html

或者也许可能有其他方法。任何想法?

+0

为什么你不包括它在你的index.html? – Demnogonis

回答

1

您可以在您选择的模板引擎中使用布局,并且每个视图都可以扩展该布局。例如,如果您使用Jade作为模板引擎。

index.js

var express = require("express"); 
var app = express(); 
var port = process.env.PORT || 7080; 

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

app.get('/', function (req, res) { 
    res.render('home'); 
}); 

app.listen(3000); 

的意见/ layout.jade

doctype html 
html 
    head 
    script(src='/javascripts/home.js') 
    link(rel='stylesheet', href='/stylesheets/style.css') 
    block title 
     title= "My Website" 
    body 
    .container 
     block content 

的意见/ home.jade

extends ./layout.jade 

block content 
    h1 Hello World! 

家。玉视图扩大了布局并覆盖了content区块。参观http://localhost:3000/返回如下:

<!DOCTYPE html> 
<html> 
    <head> 
    <script src="/javascripts/home.js"></script> 
    <link rel="stylesheet" href="/stylesheets/style.css"> 
    <title>My Website</title> 
    </head> 
    <body> 
    <div class="container"><h1>Hello World!</h1></div> 
    </body> 
</html> 
+0

我得到了模板引擎的概念,但它使简单的事情变得更加复杂。感谢您的答案btw。 :) –

+0

不幸的是,Node不能像PHP一样工作,所以我认为这是你最好的选择。如果有人有另一种选择,我会很感兴趣。 – MrWillihog

+0

是的不幸。我使用Express提供sendFile选项,但不允许在发送之前动态修改文件。但是我发现只有这个功能的ejs比所有模板引擎好一点。 –

0

做一个公共文件夹根目录

然后在主app.js/server.js

添加以下行: -

`var express = require('express'), 
bodyParser = require('body-parser'), 
userRoutes = require('./routes/user'), 
mongoose = require('mongoose'); 
var app = express(); 
mongoose.connect('mongodb://localhost/meanDemo'); 
app.use(bodyParser.json());  // to support JSON-encoded bodies 
app.use(bodyParser.urlencoded({  // to support URL-encoded bodies 
extended: true 
})); 
app.use(express.static('public')); 
app.engine('html', require('ejs').renderFile); 
app.set('view engine', 'html'); 
app.use('/', userRoutes); 
app.get('/',function(req, res){ 
res.render('userlist'); 
}); 
app.listen(3000); 
console.log("sever started at 3000"); 

`

然后在视图中使用/*filename将/将您的公共目录