HTTP協(xié)議
HTTP服務(wù)器
'use strict';
// 導(dǎo)入http模塊:
var http = require('http');
// 創(chuàng)建http server暇务,并傳入回調(diào)函數(shù):
var server = http.createServer(function (request, response) {
// 回調(diào)函數(shù)接收request和response對(duì)象,
// 獲得HTTP請(qǐng)求的method和url:
console.log(request.method + ': ' + request.url);
// 將HTTP響應(yīng)200寫入response, 同時(shí)設(shè)置Content-Type: text/html:
response.writeHead(200, {'Content-Type': 'text/html'});
// 將HTTP響應(yīng)的HTML內(nèi)容寫入response:
response.end('<h1>Hello world!</h1>');
});
// 讓服務(wù)器監(jiān)聽8080端口:
server.listen(8080);
console.log('Server is running at http://127.0.0.1:8080/');
在命令提示符下運(yùn)行該程序
$ node hello.js
Server is running at http://127.0.0.1:8080/
不要關(guān)閉命令提示符,直接打開瀏覽器輸入http://localhost:8080,即可看到服務(wù)器響應(yīng)的內(nèi)容:
Paste_Image.png
GET: /
GET: /favicon.ico
文件服務(wù)器
資源下載地址
https://github.com/michaelliao/learn-javascript
Paste_Image.png
將一個(gè)字符串解析為一個(gè)Url對(duì)象:
'use strict';
var url = require('url');
console.log(url.parse('http://user:pass@host.com:8080/path/to/file?query=string#hash'));
結(jié)果
Url {
protocol: 'http:',
slashes: true,
auth: 'user:pass',
host: 'host.com:8080',
port: '8080',
hostname: 'host.com',
hash: '#hash',
search: '?query=string',
query: 'query=string',
pathname: '/path/to/file',
path: '/path/to/file?query=string',
href: 'http://user:pass@host.com:8080/path/to/file?query=string#hash' }
完整代碼
urls.js
'use strict';
var url = require('url');
// parse url:
console.log(url.parse('http://user:pass@host.com:8080/path/to/file?query=string#hash'));
// parse incomplete url:
console.log(url.parse('/static/js/jquery.js?name=Hello%20world'));
// construct a url:
console.log(url.format({
protocol: 'http',
hostname: 'localhost',
pathname: '/static/js',
query: {
name: 'Nodejs',
version: 'v 1.0'
}
}));
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?name=Hello%20world',
query: 'name=Hello%20world',
pathname: '/static/js/jquery.js',
path: '/static/js/jquery.js?name=Hello%20world',
href: '/static/js/jquery.js?name=Hello%20world' }
http://localhost/static/js?name=Nodejs&version=v%201.0
文件服務(wù)器file_server.js
'use strict';
var
fs = require('fs'),
url = require('url'),
path = require('path'),
http = require('http');
// 從命令行參數(shù)獲取root目錄瘪撇,默認(rèn)是當(dāng)前目錄:
var root = path.resolve(process.argv[2] || '.');
console.log('Static root dir: ' + root);
// 創(chuàng)建服務(wù)器:
var server = http.createServer(function (request, response) {
// 獲得URL的path,類似 '/css/bootstrap.css':
var pathname = url.parse(request.url).pathname;
// 獲得對(duì)應(yīng)的本地文件路徑,類似 '/srv/www/css/bootstrap.css':
var filepath = path.join(root, pathname);
// 獲取文件狀態(tài):
fs.stat(filepath, function (err, stats) {
if (!err && stats.isFile()) {
// 沒有出錯(cuò)并且文件存在:
console.log('200 ' + request.url);
// 發(fā)送200響應(yīng):
response.writeHead(200);
// 將文件流導(dǎo)向response:
fs.createReadStream(filepath).pipe(response);
} else {
// 出錯(cuò)了或者文件不存在:
console.log('404 ' + request.url);
// 發(fā)送404響應(yīng):
response.writeHead(404);
response.end('404 Not Found');
}
});
});
server.listen(8080);
console.log('Server is running at http://127.0.0.1:8080/');
命令行運(yùn)行
node file_server.js D:\workspace\js\static
瀏覽器
http://localhost:8080/static/index.html
Paste_Image.png
完整代碼
js目錄
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Index</title>
<link rel="stylesheet" href="css/uikit.min.css" />
<script src="js/jquery.min.js"></script>
<script>
$(function () {
$('#code').click(function () {
window.open('https://github.com/michaelliao/learn-javascript/tree/master/samples/node/http');
});
});
</script>
</head>
<body>
<div id="header" class="uk-navbar uk-navbar-attached">
<div class="uk-container x-container">
<div class="uk-navbar uk-navbar-attached">
<a href="index.html" class="uk-navbar-brand"><i class="uk-icon-home"></i> Learn Nodejs</a>
<ul id="ul-navbar" class="uk-navbar-nav">
<li><a target="_blank" >JavaScript教程</a></li>
<li><a target="_blank" >Python教程</a></li>
<li><a target="_blank" >Git教程</a></li>
</ul>
</div>
</div>
</div><!-- // header -->
<div id="main">
<div class="uk-container">
<div class="uk-grid">
<div class="uk-width-1-1 uk-margin">
<h1>Welcome</h1>
<p><button id="code" class="uk-button uk-button-primary">Show me the code</button></p>
</div>
</div>
</div>
</div>
<div id="footer">
<div class="uk-container">
<hr>
<div class="uk-grid">
<div class="uk-width-1-1">
<p>Copyright?2015-2016</p>
</div>
</div>
</div>
</div>
</body>
</html>
file_server.js
'use strict';
//node file_server.js D:\workspace\js\http\static
//http://127.0.0.1:8080/index.html
var
fs = require('fs'),
url = require('url'),
path = require('path'),
http = require('http');
var root = path.resolve(process.argv[2] || '.');
console.log('process.argv[2]: ' + process.argv[2]);// D:\workspace\js\http\static
console.log('Static root dir: ' + root);//D:\workspace\js\http\static
var server = http.createServer(function (request, response) {
var
pathname = url.parse(request.url).pathname,
filepath = path.join(root, pathname);
console.log('request.url: ' + request.url);///index.html
console.log('request.pathname: ' + url.parse(request.url).pathname);// /index.html
console.log('filepath: ' + filepath);//D:\workspace\js\http\static\index.html
fs.stat(filepath, function (err, stats) {
if (!err && stats.isFile()) {
console.log('200 ' + request.url);
response.writeHead(200);
fs.createReadStream(filepath).pipe(response);
} else {
console.log('404 ' + request.url);
response.writeHead(404);
response.end('404 Not Found');
}
});
});
server.listen(8080);
console.log('Server is running at http://127.0.0.1:8080/');
練習(xí)
在瀏覽器輸入http://localhost:8080/ 時(shí)才漆,會(huì)返回404,原因是程序識(shí)別出HTTP請(qǐng)求的不是文件佛点,而是目錄醇滥。請(qǐng)修改file_server.js,如果遇到請(qǐng)求的路徑是目錄超营,則自動(dòng)在目錄下依次搜索index.html鸳玩、default.html,如果找到了演闭,就返回HTML文件的內(nèi)容不跟。
// 創(chuàng)建服務(wù)器:
var server = http.createServer(function (request, response) {
// 獲得URL的path,類似 '/css/bootstrap.css':
var pathname = url.parse(request.url).pathname;
// 獲得對(duì)應(yīng)的本地文件路徑米碰,類似 '/srv/www/css/bootstrap.css':
var filepath = path.join(root, pathname);
var promise_f=function(resolve,reject){
fs.stat(filepath, function (err, stats) {
if (!err) {
if(stats.isFile()){
resolve(filepath);
}else if(stats.isDirectory()){
console.log('isDirectory' + request.url);
var filename=path.join(root+pathname,'index.html')
console.log('search' + filename);
fs.stat(filename,function(err,stats){
if (!err&&stats.isFile()) {
resolve(filename);
}
else{
reject('404 ' + request.url);
}
})
filename=path.join(root+pathname,'default.html')
console.log('search' + filename);
fs.stat(filename,function(err,stats){
if (!err&&stats.isFile()) {
resolve(filename);
}else{
reject('404 ' + request.url);
}
})
}
}else{
// 發(fā)送404響應(yīng):
reject('404 ' + request.url);
}
});
};
// 獲取文件狀態(tài):
new Promise(promise_f)
.then(function(res){
// 沒有出錯(cuò)并且文件存在:
console.log('200 ' + request.url);
// 發(fā)送200響應(yīng):
response.writeHead(200);
// 將文件流導(dǎo)向response:
fs.createReadStream(filepath).pipe(response);
}).catch(function(err){
// 出錯(cuò)了或者文件不存在:
console.log('404 ' + request.url);
response.writeHead(404);
response.end('404 Not Found');
});
});