关于sendFile()函数。
ExpressJS提供sendFile()函数,它基本上将HTML文件发送到浏览器,然后由浏览器自动解释。我们需要做的就是在每个路由中提供适当的HTML文件。
我将开发简单的网站,包括3页,即主页,关于页面,网站链接页面。我将使用Bootstrap进行设计,使用jQuery进行事件处理。
Server.js
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
//__dirname : It will resolve to your project folder.
});
app.get('/about',function(req,res){
res.sendFile(path.join(__dirname+'/about.html'));
});
app.get('/sitemap',function(req,res){
res.sendFile(path.join(__dirname+'/sitemap.html'));
});
app.listen(3000);
console.log("访问地址:http://127.0.0.1:3000/");
index.html
<html>
<head>
<title>Express HTML</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div style="margin:100px;">
<nav class="navbar navbar-inverse navbar-static-top">
<div class="container">
<a class="navbar-brand" href="/">Express HTML</a>
<ul class="nav navbar-nav">
<li class="active">
<a href="/">Home</a>
</li>
<li>
<a href="/about">About</a>
</li>
<li>
<a href="/sitemap">Sitemap</a>
</li>
</ul>
</div>
</nav>
<div class="jumbotron" style="padding:40px;">
<h1>Hello, world!</h1>
<p>This is a simple hero unit, a simple jumbotron-style
component for calling extra attention to featured content or information.</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
</div>
</div>
</body>
</html>