web服務(wù)器介紹
web服務(wù)器一般指網(wǎng)絡(luò)服務(wù)器飞主,是指駐留于因特網(wǎng)上某種類型計(jì)算機(jī)程序逆屡,可以向?yàn)g覽器等web客戶端提供文檔誉察,也可以放置網(wǎng)站与涡,讓全世界瀏覽;可以放置數(shù)據(jù)文件持偏,讓全世界下載递沪。目前最主流的三個(gè)web服務(wù)器是Apache Nginx IIS
nodejs創(chuàng)建web服務(wù)器
const?http?=?require("http");
http
??.createServer((req,?res)?=>?{
????res.writeHead(200,?{?"Content-Type":?"text/html;charset='utf-8'"?});
????res.write("你好,nodejs");
????res.end();
??})
??.listen("8000");
實(shí)現(xiàn)靜態(tài)web服務(wù)
思路:獲取文件路徑综液,將文件返回給瀏覽器款慨。
const?http?=?require("http");
const?fs?=?require("fs");
http
??.createServer((req,?res)?=>?{
????let?pathName?=?req.url;?//獲取路徑
????if?(pathName?==?"/")?{
??????//默認(rèn)加載首頁
??????pathName?=?"/index.html";
????}
????if?(pathName?!=?"/favicon.ico")?{
??????//過濾'/favicon.ico',req.url是兩個(gè)路徑。
??????//文件操作谬莹,獲取static下面的index.html
??????fs.readFile("static/"?+?pathName,?function(err,?data)?{
????????if?(err)?{
??????????//找不到指定文件
??????????console.log(err);
??????????return;
????????}?else?{
??????????res.writeHead(200,?{?"Content-Type":?"text/html;charset='utf-8'"?});
??????????res.write(data);
??????????res.end();
????????}
??????});
????}
??})
??.listen("8000");
一個(gè)簡(jiǎn)單的web服務(wù)器創(chuàng)建完畢檩奠。
注意事項(xiàng):此文件為server.js,static文件問當(dāng)前文件夾下的文件附帽。
存在問題埠戳,頭文件設(shè)置是text/html,雖然能加載出其他文件蕉扮,但是不能正常渲染
解決辦法:根據(jù)文件改變請(qǐng)求頭整胃。
1、path模塊var extname = path.extname("index.html")可輸出.html
2喳钟、編寫方法根據(jù)后綴名輸出對(duì)應(yīng)的頭文件屁使,
?function getMime(extname)?{
??switch?(extname)?{
????case?".html":
??????return?"text/html";
????case?".css":
??????return?"text/css";
????case?".js":
??????return?"text/javascript";
????default:
??????return?"text/html";
??}
};
var mime = getMime(extname)
res.writeHead(200,?{?"Content-Type":?`${mime};charset='utf-8'`?});
除此之外可以使用mime.json文件改變頭文件
思路找一個(gè)mime.json文件,使用readFileSync()讀取json文件匹配頭文件并返回
const?fs?=?require("fs");
module.exports?=?function(extname)?{
??var?res?=?fs.readFileSync("./static/mime.json");
??console.log(JSON.parse(res.toString())[extname]);
??return?JSON.parse(res.toString())[extname];
};
找不到文件奔则,返回404頁面