方法1:利用 Express 托管靜態文件,詳情查看這里
方法2:使用fs模塊提供的readFile方法打開文件,讓其以text/html的形式輸出。
代碼:
var express = require('express');
var fs=require("fs");
var app = express();
//方法1:通過express.static訪問靜態文件,這里訪問的是ajax.html
// app.use(express.static("./"));
//方法2:使用fs.readFile打開html文件
app.get("/helloworld.html", function(request, response) {
fs.readFile("./"+request.path.substr(1),function(err,data){
// body
if(err){
console.log(err);
//404:NOT FOUND
response.writeHead(404,{"Content-Type":"text/html"});
}
else{
//200:OK
response.writeHead(200,{"Content-Type":"text/html"});
response.write(data.toString());
}
response.end();
});
});
app.listen(3000, function() { //監聽http://127.0.0.1:3000端口
console.log("server start");
});
瀏覽器訪問,分別輸入http://127.0.0.1:3000/hello_static.html和http://127.0.0.1:3000/hello_fs.html,結果: