express-2-中間件



/public/index.html
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Title</titel>
</head>
<body>
<p>中間件</p>
</body>
/app.js
var http=require("http");
var express = require("express");
var app = express();

//自定義中間件
//中間件是按順序執行,如果沒有用到next,則會停止
app.use("/",function(req,res,next){
console.log("進入自定義中間件");
next();
});

//掛載中間件 ,第一個參數是指定路徑,默認值是“/”
//傳入public,能訪問到靜態頁面,express.static爲express自帶中間件
app.use("/",express.static(__dirname+"/public"))

app.all("/index",function(req,res){
console.log("hello server")
res.send("hello browser!");
res.end();
})
http.createServer(app).listen(3000,function(err){
if(err){
console.log("服務器錯誤")
}else{
console.log("服務器啓動成功,監聽3000端口")
}
})

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章