安裝 Node
用Node實(shí)現(xiàn)的簡(jiǎn)單Web服務(wù)器
創(chuàng)建一個(gè) hello.js 文件
var http = require('http');
http.createServer(function(req,res){
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello world!');
}).listen(3000);
console.log('Server started on localhost:3000');
在和 helloWorld.js 同一個(gè)目錄下飒责,輸入 node hello.js
然后打開(kāi)瀏覽器訪問(wèn) http://localhost:3000
第一個(gè) Web 服務(wù)器就建成啦
路由
路由是指處理客戶端發(fā)出的不同請(qǐng)求路徑的機(jī)制邑贴。
比如:如何處理以下的請(qǐng)求
http://localhost:3000/
http://localhost:3000/about
http://localhost:3000/may-not-exist
給以上的服務(wù)器增加路由處理
var http = require('http');
http.createServer(function(req,res){
// 規(guī)范化 url,去掉查詢字符串签则、可選的反斜杠,并把它變成小寫(xiě)
var path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase();
switch(path) {
case '':
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Homepage');
break;
case '/about':
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('About');
break;
default:
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
break;
}
}).listen(3000);
console.log('Server started on localhost:3000');
靜態(tài)資源服務(wù)
用 Node 提供靜態(tài)資源只適用于初期的小型項(xiàng)目铐料,對(duì)于比較大的項(xiàng)目渐裂,你應(yīng)該會(huì)想用 Nginx 或 CDN 之類的代理服務(wù)器來(lái)提供靜態(tài)資源豺旬。
Node 處理靜態(tài)資源文件,必須打開(kāi)文件柒凉,讀取其中的內(nèi)容族阅,然后將這些內(nèi)容發(fā)送給瀏覽器。
準(zhǔn)備工作:
創(chuàng)建一個(gè)名為 public 的目錄膝捞,
在這個(gè)目錄下創(chuàng)建文件 home.html坦刀、about.html、notfound.html蔬咬,
創(chuàng)建子目錄 img鲤遥,在其中添加一個(gè)名為logo.jpg 的圖片。
在你的 HTML 文件中這樣引用 logo:<img src="/img/logo.jpg" alt="logo">
修改hello.js
var http = require('http'),
fs = require('fs');
function serveStaticFile(res, path, contentType, responseCode) {
if(!responseCode) responseCode = 200;
fs.readFile(__dirname + path, function(err,data) {
if(err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('500 - Internal Error');
} else {
res.writeHead(responseCode, { 'Content-Type': contentType });
res.end(data);
}
});
}
http.createServer(function(req,res){
// 規(guī)范化 url计盒,去掉查詢字符串渴频、可選的反斜杠,并把它變成小寫(xiě)
var path = req.url.replace(/\/?(?:\?.*)?$/, '') .toLowerCase();
switch(path) {
case '':
serveStaticFile(res, '/public/home.html', 'text/html');
break;
case '/about':
serveStaticFile(res, '/public/about.html', 'text/html');
break;
case '/img/logo.jpg':
serveStaticFile(res, '/public/img/logo.jpg', 'image/jpeg');
break;
default:
serveStaticFile(res, '/public/404.html', 'text/html', 404);
break;
}
}).listen(3000);
console.log('Server started on localhost:3000');
Express
安裝express :npm install --save express
創(chuàng)建 meadowlark.js 文件
var express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
// 定制 404 頁(yè)面
app.use(function(req, res){
res.type('text/plain');
res.status(404);
res.send('404 - Not Found');
});
// 定制 500 頁(yè)面
app.use(function(err, req, res, next){
console.error(err.stack);
res.type('text/plain');
res.status(500);
res.send('500 - Server Error');
});
app.listen(app.get('port'), function(){
console.log( 'Express started on http://localhost:' +
app.get('port') + '; press Ctrl-C to terminate.' );
});
啟動(dòng)這個(gè)服務(wù)器 node meadowlark.js
北启,然后訪問(wèn) http://localhost:3000
最后卜朗, 給首頁(yè)和關(guān)于頁(yè)面加上路由。在 404 處理器之前加上兩個(gè)新路由
app.get('/', function(req, res){
res.type('text/plain');
res.send('Meadowlark Travel');
});
app.get('/about', function(req, res){
res.type('text/plain');
res.send('About Meadowlark Travel');
});
// 定制 404 頁(yè)面
app.use(function(req, res, next){
res.type('text/plain');
res.status(404);
res.send('404 - Not Found');
});