使用Node建立一個(gè)Web服務(wù)
新建一個(gè) server.js文件,輸入一下代碼:
var http = require('http');
http.createServer(function (req,res) {
//回調(diào)函數(shù)當(dāng)瀏覽器發(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 會(huì)顯示 hello world色瘩。
Connect 模塊
Connect模塊可以更好的支持服務(wù)端與客戶端的HTTP請求交互逸寓。
- 一個(gè)模塊化的組件叫做middleware,可以將業(yè)務(wù)應(yīng)用注冊到特定的情景
- 使用回調(diào)連接middleware
- 一個(gè)Connect應(yīng)用使用 dispatcher 實(shí)例處理請求
- Connect不是Core Module 所以需要導(dǎo)入 npm install connect
npm導(dǎo)入Connect模塊后泥栖,寫一個(gè)Connect sever:
var connect = require('connect');
var app = connect();
app.listen(3000);
console.log('Server is running at http://localhost:3000');
運(yùn)行勋篓,瀏覽器會(huì)顯示 Cannot GET/,因?yàn)闆]有middlewre處理GET HTTP請求耙蔑。
Connect middleware
middleware其實(shí)就是個(gè)有唯一簽名的function
定義一個(gè)middleware需要包含三個(gè)參數(shù):
- req: 請求信息
- res: 返回信息
- next: 連接下一個(gè)middleware
當(dāng)middleware定義好后甸陌,使用app.use( functionName )注冊到Connect應(yīng)用盐股。
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ù)個(gè)middleware,而這些middleware 可以通過next相互連接牲尺。
Connect執(zhí)行middleware的順序是先進(jìn)先出FIFO,直到?jīng)]有middleware可以執(zhí)行或者有一個(gè)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這個(gè)功能可以使Connect根據(jù)不同的請求path作出不同的相應(yīng)(類似路由)
具體方法是:在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í)行下一個(gè)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è)置路徑參數(shù)
app.use('/goodbye',goodbyeWorld);//設(shè)置路徑參數(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 提供了更時(shí)髦的web服務(wù)端特性的支持蜒简,但是還是不很完善搓茬。在社區(qū)廣大開發(fā)者队他,特別是TJ Holowaychuk的共同努力下,出現(xiàn)了更完善的Web開發(fā)框架包Express锡凝,Express是基于Connect的垢啼。