nodejs创建http服务器

之前有简单介绍nodejs的一篇文章(http://www.cnblogs.com/fangsmile/p/6226044.html)

HTTP服务器

Node内建有一个模块,利用它可以很容易创建基本的HTTP服务器。请看下面案例。

my_web_server.js

1 var http = require('http');
2 http.createServer(function (req, res) {
3 res.writeHead(200, {'Content-Type': 'text/plain'});
4 res.end('Hello World\n');
5 }).listen(8080);
6
7 console.log('Server running on port 8080.');

在上面,我说是的基本HTTP服务器。该例中所创建的并不是一个功能全面的HTTP服务器,它并不能处理任何HTML文件、图片。事实上,无论你请求什么,它都将返回“Hello World”。你运行该代码,并在浏览器中输入“http://localhost:8080”,你将看见该文本。

$ node my_web_server.js  

现在你可能已经注意到一些不一样的东西。你的Node.js应用并没有退出。这是因为你创建了一个服务器,你的Node.js应用将继续运行,并响应请求,直到你关闭它。

如果你希望它成为一个全功能的Web服务器,你必须检查所收到的请求,读取合适的文件,并返回所请求的内容。

首先实现一个处理静态资源的函数,其实就是对本地文件的读取操作,这个方法已满足了上面说的静态资源的处理。

 var http = require('http');
var fs = require("fs");
http.createServer(function (req, res) {
staticResHandler("G:/nodemodule/home_index.html", "html", res)
}).listen(8080);
function staticResHandler(localPath, ext, response) {
fs.readFile(localPath, "binary", function (error, file) {
if (error) {
response.writeHead(500, { "Content-Type": "text/plain" });
response.end("Server Error:" + error);
} else {
response.writeHead(200, { "Content-Type": 'text/html' });
response.end(file, "binary");
}
});
}
console.log('Server running on port 8080.');

进一步使用nodejs创建web服务器处理get、post请求

path.js :

  var http = require('http');
var fs = require('fs');
var assert = require('assert');
var path = require('path');
var url = require('url'); var config = {
port:81
}
var sum = 0;
var response = {
"content":[
{
"type":"11111",
"name":"hello world"
},
{
"type":"22222",
"name":"world Map"
} ]
} http.createServer(function(req,res){
sum ++;
var pathName = url.parse(req.url).pathname;
var localPath = "";
var ext = path.extname(pathName);
var Type = req.method;
if(Type =='POST'){
var resData = {};
var body = '';
req.on('data',function(data){
body += data;
console.log('data' + data);
});
req.on('end',function(data){
var len = body.split('&').length;
if(len > 0){
for(var i=0;i<len;i++){
var key = body.split('&')[i];
resData[key.split('=')[0]] = key.split('=')[1];
}
}
res.writeHead(200,{'Content-Type':'application/x-json'});
res.end(JSON.stringify(resData),'binary');
}); }
else if(Type =='GET'){
if(pathName =='/'){
pathName = '/html/index.html';
}
if(ext.length > 0){
localPath = '.' + pathName;
}
else{
localPath ='./src' + pathName;
}
console.log('localPath:' + localPath);
fs.exists(localPath,function(exists){
if(exists){
console.log(localPath + ' is exists');
fs.readFile(localPath,'binary',function(err,file){
if(err){
res.writeHead(500,{'Content-Type':'text/plain'});
res.end('server Error:' + err);
}
else{
res.writeHead(200,{'Content-Type':getContentTypeByExt(ext)});
if(ext === '.json'){
res.end(JSON.stringify(response),'binary');
}
else{
res.end(file,'binary');
} }
})
}
else{
res.writeHead(400,{'Content-Type':'text/plain'});
res.end('404:File Not found');
} })
} }).listen(config.port); function getContentTypeByExt(ext) {
ext = ext.toLowerCase();
if (ext === '.htm' || ext === '.html')
return 'text/html';
else if (ext === '.js')
return 'application/x-javascript';
else if (ext === '.css')
return 'text/css';
else if (ext === '.jpe' || ext === '.jpeg' || ext === '.jpg')
return 'image/jpeg';
else if (ext === '.png')
return 'image/png';
else if (ext === '.ico')
return 'image/x-icon';
else if (ext === '.zip')
return 'application/zip';
else if (ext === '.doc')
return 'application/msword';
else if (ext === '.json')
return 'application/x-json';
else
return 'text/plain';
} console.log('new server is running: http://127.0.0.1:81')

index.html

<html>
<head>
<title>Sample Page</title>
<meta charset="UTF-8">
</head>
<link rel="stylesheet" href="../css/index.css"/>
<body>
Hello World!
<div class="music_class">
<img src="../img/music_class.png" alt="分类图片"/>
</div>
<div>
<div>get请求获取的数据:</div>
<ul class="music_category_list">
</ul>
</div>
<div>
<button class='postClick'>点击POST请求</button>
<div class='postDiv'>
<span>post请求获取的数据:</span>
<span class='postData'></span>
</div>
</div>
</body>
<script src="../js/lib/jquery-1.11.3.min.js"></script>
<script src="../js/page/index.js"></script>
</html>

index.js

 $(document).ready(function(){
function createEle(){
var img = new Image();
img.src = "../img/music_hot.png";
img.onload = function(){
var imgDom = '<img src="../img/music_hot.png"/>';
$('.music_class').append(imgDom);
}
}
createEle();
(function getDate(){
var XHR = $.ajax({
timeout : 20000,
dataType : 'json',
type : 'GET',
url : '../package.json',
data : '',
beforeSend : function (request) {
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
},
complete : function(XMLHttpRequest, status) {
if (status == 'timeout') {
//theUIApp.tip($("body"), "网络异常,请检查网络");
util.toast("网络异常,请检查网络");
}
},
success : function (result) {
var LiLength = result.content.length;
if(LiLength > 0){
for(var i=0;i<LiLength;i++){
var inp = '<li>' + result.content[i].name + '</li>';
$('.music_category_list').append(inp);
}
}
},
error : function (result) {
console.log(result)
}
});
})(); $('.postClick').click(function(){
Post();
}) function Post(){
var option = {
name:'zhangsan',
age:'15'
}
var XHR = $.ajax({
timeout : 20000,
dataType : 'json',
type : 'POST',
url : '../package.json',
data : option,
beforeSend : function (request) {
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
},
complete : function(XMLHttpRequest, status) {
if (status == 'timeout') {
//theUIApp.tip($("body"), "网络异常,请检查网络");
util.toast("网络异常,请检查网络");
}
},
success : function (result) {
if(result){
$('.postData').text(result.name);
}
},
error : function (result) {
console.log(result)
}
});
}
})

index.css

 @charset "utf-8";
html{ height: 100%}
body{
font-family:"Microsoft YaHei",Arial,Helvetica,sans-serif,"宋体";
font-size:3.5rem;
}
li{
list-style-type:none;
}
.music_class{
width:100%;
margin:10px;
}
.music_class img{
width:95%;
}
.music_category_list{
margin:10px;
}
.music_category_list li{
width:95%;
margin:5px;
padding:5px;
border:2px solid #ccc;
}
.postData{
width:100%;
color:blue;
fonst-size:20px;
text-align:center;
}
button{
font-size:30px;
width:300px;
height:100px;
}

建议服务器的相关代码下载地址:http://files.cnblogs.com/files/fangsmile/nodejs-http%E6%9C%8D%E5%8A%A1%E5%99%A8.zip

下载下来运行:node path    然后访问 http://127.0.0.1:81/index.html

上一篇:php微服务框架 PHP-MSF 的容器部署和使用


下一篇:linux安装python