node.js建立簡單Http服務(wù)(四)

引入http基本模塊實(shí)現(xiàn)服務(wù)

var http = require('http');
//文件讀寫模塊
var fs = require('fs');
//路徑相關(guān)模塊
var path = require('path');

http.createServer(function(req, res){
    if(req.url === '/'){
        //輸出內(nèi)容并結(jié)束響應(yīng),這兩行可以合成end('hello index')
        // res.write('hello index');
        // res.end();
        res.setHeader('Content-Type','text/plain; charset=utf-8');
        res.end('hello,<h1>我的主頁</h1>');
    }else if(req.url === '/test'){
        //直接響應(yīng)html
        res.setHeader('Content-Type','text/html; charset=utf-8');
        res.end('hello <h1>test</h1>');
    }else if(req.url === '/page'){
        //響應(yīng)html文件
        //__dirname表示當(dāng)前文件所在的文件夾絕對(duì)路徑,__filename為當(dāng)前文件絕對(duì)路徑,非全局
        //類似于沙箱操作的參數(shù)(function(__dirname,__filename){...})('文件夾路徑','文件路徑')
        //path.join這一語句輸出d:/nodespace/test/htmls/main.html,屏蔽了不同系統(tǒng)分隔符的區(qū)別
        //如果出現(xiàn)異常,err不為空
        fs.readFile(path.join(__dirname,'htmls','main.html'),function(err,data){
            //遇到異常直接拋出去
            if(err){
                throw err;
            }
            //把讀取到的html文件直接返回給瀏覽器
            res.end(data);
        })
    }else{
        res.end('not found!')
    }
}).listen(8080, function(){
    console.log('server is running...')
})

加載靜態(tài)資源文件,首先要安裝mime模塊,主要是根據(jù)后綴識(shí)別類型
安裝和使用:https://www.npmjs.com/package/mime

image.png

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容