node.js搭建简单的HTTP服务器

###参考资料
《Node.js入门经典》第5章

###1. 最简单的HTTP服务器

1
2
3
4
5
6
var http = require('http');
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type':'text/plain'});
res.end('Hello, I\'m an HTTP server.');
}).listen(3000);
console.log('Server running at http://127.0.0.1:3000');

###2. 路由控制的HTTP服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var http = require('http'),
url = require('url');
http.createServer(function(req, res){
var pathname = url.parse(req.url).pathname;
if (pathname ==='/'){
res.writeHead(200, {'Content-Type':'text/plain'});
res.end('Hello, I\'m an HTTP server.');
} else if (pathname === '/about'){
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('About us\n');
} else if (pathname === '/redirect') {
// 重定向
res.writeHead(302, {'Location':'/'});
res.end();
} else{
res.writeHead(404, {'Content-Type':'text/plain'});
res.end('Page not found\n');
}
}).listen(3000,"127.0.0.1");
console.log('Server running at http://127.0.0.1:3000');
Share