單頁面的部署
摘要:1、我也不知道是不是叫單頁面部署,就是把你做的html頁面,監聽起來,然後在瀏覽器上面輸入地址就能訪問了;
2、其實跟我們昨天寫的一樣,就是把html文件讀取出來,然後在寫到瀏覽器頁面上response.end(data)/response.write(data);response.end()
- 訪問index.html
- 在瀏覽器中輸入“127.0.0.1:8000”就能得到index.html的頁面了;
目錄結構:
-----public---index.html
-----http.js
//======================
const http = require("http");
const fs = require("fs");
http.createServer(function(req,res){
fs.readFile("public/index.html", function(err,data){
res.writeHead(200,{"Content-Type":"text/html"});
res.write(data);
res.end();
})
}).listen(8000,"127.0.0.1")
2、訪問index.html中的css/javascript文件;
——-1、如果直接在index.html中鏈接css/js文件,還是按照什麼的寫法,是訪問不到css/js文件的;
——-2、按照上面的思路,這兩個文件(css、js),還是可以用“fs”模塊讀取然後寫到響應中去write();
目錄結構:
-----public---index.html
---index.css
---index.js
-----http.js
//demo=================================
const http = require("http");
const fs = require("fs");
const url = require("url");
http.createServer(function(req,res){
var pathname = url.parse(req.url).pathname;
var ext = pathname.match(/(\.[^.]+|)$/)[0];
switch (ext){
case ".css" :
case ".js" :
fs.readFile("./public/"+req.url, function(err,data){
res.writeHead(200,{"Content-Type":{
".css" : "text/css",
".js" : "application/javascript"
}[ext]
});
res.write(data);
res.end();
})
break;
default :
fs.readFile("public/index.html", function(err,data){
res.writeHead(200,{"Content-Type":"text/html"});
res.write(data);
res.end();
})
}
}).listen(8000,"127.0.0.1")