如何使用node.js在html中包含静态文件
这不是一个关于express.static()的问题
我有一个应用程序,我需要服务多个页面具有相同的JS和CSS依赖关系。 因此,编写css和js包括在每个页面上使用<script>
或<link>
标签是不好的做法。
我正在寻找一个类似php的方式来做到这一点。 由于PHP会处理所有的PHP代码,并发送编译的HTML,我想同样可以用js在节点服务器上完成。
所以服务器会有点像下面这样:
- 从resources.html获取html
- 把html上面的html推到index.html
- 发送index.html
或者也许还有其他的方法。 任何想法?
您可以使用您select的模板引擎使用布局,每个视图可以扩展该布局。 例如,如果您使用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!
home.jade视图扩展了布局并覆盖了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>
在根目录中创build一个公用文件夹
然后在主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
名将/你的公共目录