node服務器中打開html文件的兩種方法


方法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.htmlhttp://127.0.0.1:3000/hello_fs.html,結果:

這里寫圖片描述


這里寫圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM