使用Node建立一個Web服務
新建一個 server.js文件,輸入一下代碼:
var http = require('http');
http.createServer(function (req,res) {
//回調(diào)函數(shù)當瀏覽器發(fā)出HTTP請求是被調(diào)用
//response頭,如果是html的話用 html/plain
res.writeHead(200,{'Content-Type' :'text/plain' });
res.write('Hello suck world');
//結(jié)束
res.end();
}).listen(3000);//監(jiān)聽3000端口
瀏覽器輸入http://localhost:3000 會顯示 hello world。
Connect 模塊
Connect模塊可以更好的支持服務端與客戶端的HTTP請求交互。
- 一個模塊化的組件叫做middleware,可以將業(yè)務應用注冊到特定的情景
- 使用回調(diào)連接middleware
- 一個Connect應用使用 dispatcher 實例處理請求
- Connect不是Core Module 所以需要導入 npm install connect

npm導入Connect模塊后,寫一個Connect sever:
var connect = require('connect');
var app = connect();
app.listen(3000);
console.log('Server is running at http://localhost:3000');
運行,瀏覽器會顯示 Cannot GET/,因為沒有middlewre處理GET HTTP請求。
Connect middleware
middleware其實就是個有唯一簽名的function
定義一個middleware需要包含三個參數(shù):
- req: 請求信息
- res: 返回信息
- next: 連接下一個middleware
當middleware定義好后,使用app.use( functionName )注冊到Connect應用。
var connect = require('connect');var app = connect();
var helloWorld = function (req,res,next) {
res.setHeader('Content-Type','text/plain');
res.end('Hello World');
};
app.use(helloWorld);
app.listen(3000);
console.log('Server is running at http://localhost:3000');```
Connect 可以注冊無數(shù)個middleware,而這些middleware 可以通過next相互連接。
Connect執(zhí)行middleware的順序是先進先出FIFO,直到?jīng)]有middleware可以執(zhí)行或者有一個middleware沒有這行next()方法。
var connect = require('connect');
var app = connect();
var logger = function (req,res,next) {
console.log(req.method,req.url);
next();
}
var helloWorld = function (req,res,next) {
res.setHeader('Content-Type','text/plain');
res.end('Hello World');
};
app.use(logger);
app.use(helloWorld);
app.listen(3000);
console.log('Server is running at http://localhost:3000');
### Mounting Connect middleware - 裝配
Mounting這個功能可以使Connect根據(jù)不同的請求path作出不同的相應(類似路由)
具體方法是:在app.user( )方法加上路徑參數(shù)
var connect = require('connect');
var app = connect();
var logger = function (req,res,next) {
console.log(req.method,req.url);
next();//表示繼續(xù)執(zhí)行下一個md
}
var helloWorld = function (req,res,next) {
res.setHeader('Content-Type','text/plain');
res.end('Hello World');
//沒有next()不用連接其他md
};
var goodbyeWorld = function (req,res,next) {
res.setHeader('Content-Type','text/plain');
res.end('Goodbye World');
//沒有next()不用連接其他md
}
app.use(logger);
app.use('/hello',helloWorld);//設置路徑參數(shù)
app.use('/goodbye',goodbyeWorld);//設置路徑參數(shù)
app.listen(3000);
console.log('Server is running at http://localhost:3000');
以上代碼瀏覽器測試:
* http://localhost:3000/hello 輸出HelloWorld
* http://localhost:3000/goodbye 輸出Goodbye World
#### 總結(jié)
Connect 提供了更時髦的web服務端特性的支持,但是還是不很完善。在社區(qū)廣大開發(fā)者,特別是TJ Holowaychuk的共同努力下,出現(xiàn)了更完善的Web開發(fā)框架包Express,Express是基于Connect的。