node—http服務(wù)器模塊

HTTP模塊-服務(wù)器

  • 1.什么是HTTP模塊

    • 通過Nodejs提供的http模塊,我們可以快速的構(gòu)建一個(gè)web服務(wù)器,也就是快速實(shí)現(xiàn)過去PHP服務(wù)器的功能(接收瀏覽器請(qǐng)求、響應(yīng)瀏覽器請(qǐng)求等)
  • 2.通過HTTP模塊實(shí)現(xiàn)服務(wù)器功能步驟

    • 2.1導(dǎo)入HTTP模塊
    • 2.2創(chuàng)建服務(wù)器實(shí)例對(duì)象
    • 2.3綁定請(qǐng)求事件
    • 2.4監(jiān)聽指定端口請(qǐng)求
let http = require("http");

// 1.創(chuàng)建一個(gè)服務(wù)器實(shí)例對(duì)象
let server = http.createServer();
// 2.注冊(cè)請(qǐng)求監(jiān)聽
server.on("request", function (req, res) {
    // res.end("www.it666.com");  // 返回?cái)?shù)據(jù)是英文,則不需要寫下面那行
    res.writeHead(200, {
        "Content-Type": "text/plain; charset=utf-8"
    });
    res.end("微雙");
});
// 3.指定監(jiān)聽的端口
server.listen(3000);
  • end方法的作用

    • 結(jié)束本次請(qǐng)求并且返回?cái)?shù)據(jù)
    • 上個(gè)示例中:res.end("微雙");
  • writeHead方法的作用

    • 告訴瀏覽器返回的數(shù)據(jù)是什么類型的,返回的數(shù)據(jù)需要用什么字符集來解析
    • 上個(gè)示例中:res.writeHead(200, {"Content-Type": "text/plain; charset=utf-8"});
web服務(wù)器簡(jiǎn)寫(鏈?zhǔn)骄幊?
  • 上個(gè)示例
let http = require('http');
http.createServer(function (req,res) {
    res.writeHead(200,{
        'Content-Type': 'text/plain;charset=utf-8'
    });
    res.end('微小雙');
}).listen(3000);

路徑分發(fā)

  • 1.什么是路徑分發(fā)?

    • 路徑分發(fā)也稱之為路由,就是根據(jù)不同的請(qǐng)求路徑返回不同的數(shù)據(jù)
  • 2.如何根據(jù)不同的請(qǐng)求路徑返回不同的數(shù)據(jù)?

    • 通過請(qǐng)求監(jiān)聽方法中的request對(duì)象,我們可以獲取到當(dāng)前請(qǐng)求的路徑
      • request對(duì)象其實(shí)是http.IncomingMessage 類的實(shí)例
    • 通過判斷請(qǐng)求路徑的地址就可以實(shí)現(xiàn)不同的請(qǐng)求路徑返回不同的數(shù)據(jù)
//根據(jù)上個(gè)示例:
let http = require('http');
http.createServer(function (req,res) {
    res.writeHead(200,{
        'Content-Type': 'text/plain;charset=utf-8'
    });
    if(req.url.startsWith('/index')){
        res.end('首頁(yè)');
    }else if(req.url.startsWith('/login')){
        res.end('登錄');
    }else{
        res.end('沒有數(shù)據(jù)');
    }

}).listen(3000);
請(qǐng)求路徑多次返回?cái)?shù)據(jù)
  • response對(duì)象其實(shí)是http.ServerResponse 類的實(shí)例

  • res.write

    • write方法不具備結(jié)束本次請(qǐng)求的功能,所以還需要手動(dòng)的調(diào)用end方法來結(jié)束本次請(qǐng)求
  • ==注意點(diǎn)==

    • 如果通過end方法來返回?cái)?shù)據(jù),那么只會(huì)返回一次
    • 如果通過write方法來返回?cái)?shù)據(jù),那么可以返回多次
let http = require("http");

// 1.創(chuàng)建一個(gè)服務(wù)器實(shí)例對(duì)象
let server = http.createServer();
// 2.注冊(cè)請(qǐng)求監(jiān)聽
server.on("request", function (req, res) {
    res.writeHead(200, {
        "Content-Type": "text/plain; charset=utf-8"
    });
    // console.log(req.url);
    if(req.url.startsWith("/index")){
        // res.end("首頁(yè)1");  // 只會(huì)返回首頁(yè)1
        // res.end("首頁(yè)2");    
        res.write("首頁(yè)1");
        res.write("首頁(yè)2");
        res.end(); 
    }else if(req.url.startsWith("/login")){
        res.end("登錄");
    }else{
        res.end("沒有數(shù)據(jù)");
    }
});
// 3.指定監(jiān)聽的端口
server.listen(3000);

響應(yīng)完整頁(yè)面(返回靜態(tài)網(wǎng)頁(yè))

  • 示例(未優(yōu)化版)
let http = require('http');
let path = require('path');
let fs = require('fs');

let server = http.createServer();
server.on('request',function (req,res) {
    if(req.url.startsWith('/index')){
        let filePath = path.join(__dirname,'www','index.html');
        fs.readFile(filePath,'utf8',function (err,content) {
            if(err){
                res.end('Error');
            }
            res.end(content);
        })
    }else if(req.url.startsWith('/login')){
        let filePath = path.join(__dirname,'www','login.html');
        fs.readFile(filePath,'utf8',function (err,content) {
            if(err){
                res.end('Error');
            }
            res.end(content);
        })
    }else{
        res.end('No data');
    }
});
server.listen(3000);
  • 優(yōu)化版(未完成版,只適合text)

  • ==注意點(diǎn)==

    • 1.加載其它的資源不能寫utf8
    • 2.如果服務(wù)器在響應(yīng)數(shù)據(jù)的時(shí)候沒有指定響應(yīng)頭, 那么在有的瀏覽器上,響應(yīng)的數(shù)據(jù)有可能無(wú)法顯示
let http = require('http');
let path = require('path');
let fs = require('fs');

let server = http.createServer();
server.on('request',function (req, res) {
    readFile(req, res);
});
server.listen(3000);

function readFile(req, res) {
    let filePath = path.join(__dirname,'www',req.url);
    fs.readFile(filePath,'utf8',function (err,content) {
        if(err){
            res.end('Error');
        }
        res.end(content);
    });
}
響應(yīng)靜態(tài)資源
  • 響應(yīng)靜態(tài)資源

    • 在給瀏覽器返回?cái)?shù)據(jù)的時(shí)候,如果沒有指定響應(yīng)頭的信息,如果沒有設(shè)置返回?cái)?shù)據(jù)的類型,那么瀏覽器不一定能正確的解析
    • ==所以無(wú)論返回什么類型的靜態(tài)資源都需要添加對(duì)應(yīng)的響應(yīng)頭信息==
  • 優(yōu)化版(上節(jié)代碼終極版本,適用各種格式)

let http = require('http');
let path = require('path');
let fs = require('fs');
let mime = require('./mime.json');

let server = http.createServer();
server.on('request',function (req, res) {
    readFile(req, res);
});
server.listen(3000);

function readFile(req, res) {
    let filePath = path.join(__dirname, "www", req.url);
    let extName = path.extname(filePath);
    let type = mime[extName];
    if(type.startsWith("text")){
        type += "; charset=utf-8;";
    }
    res.writeHead(200, {
        "Content-Type": type
    });
    fs.readFile(filePath, function (err, content) {
        if(err){
            res.end("Server Error");
        }
        res.end(content);
    });
}
返回靜態(tài)資源封裝
let path = require('path');
let fs = require('fs');
let mime = require('./mime.json');  // 這個(gè)文件是封裝的各種格式

function readFile(req, res, rootPath) {
    let filePath = path.join(rootPath ,req.url);
    let extName = path.extname(filePath);
    let type = mime[extName];
    if(type.startsWith('text')){
        type += ';charset=uft-8;';
    }
    res.writeHead(200,{
        'Content-Type': type
    });
    fs.readFile(filePath,function (err,content) {
        if(err){
            res.end('Error');
        }
        res.end(content);
    });
}

exports.StaticServer = readFile;
  • 測(cè)試:
    • 上面封裝好代碼的調(diào)用示例(需要有一個(gè)名為www的文件夾,里面裝有測(cè)試文件)
let http = require('http');
let path = require('path');
let ss = require('./StaticServer.js');

let server = http.createServer();
server.on('request',function (req, res) {
    let rootPath = path.join(__dirname, 'www');
    ss.StaticServer(req, res, rootPath);
});
server.listen(3000);

最后編輯于
?著作權(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),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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