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
nodejs创建http服务器的更多相关文章
- Nodejs创建HTTPS服务器
Nodejs创建HTTPS服务器 从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发.Nodejs框架是基于V8的引擎,是目前速度最快的Jav ...
- NodeJs 创建 Web 服务器
以下是演示一个最基本的 HTTP 服务器架构(使用8081端口),创建 ser.js 文件,代码如下所示: var http = require('http'); var fs = require(' ...
- Nodejs创建https服务器(Windows 7)
为了实验一下WebRTC,搭了个简单的https服务器.说说步骤: 生成OpenSSL证书 使用Nodejs的https模块建立服务器 OpenSSL 证书 我机子Windows 7,安装了Cygwi ...
- Express与NodeJs创建服务器的两种方法
NodeJs创建Web服务器 var http = require('http'); var server = http.createServer(function(req, res) { res.w ...
- Nodejs+Express创建HTTPS服务器
为了使我的Nodejs服务器提供HTTPS服务,学习了一下如何利用express创建https服务器,现记录如下.(一点一点的积累与掌握吧) 1. Http与Https 介绍 HTTP: 超文本传输协 ...
- 使用nodejs的net模块创建TCP服务器
使用nodejs的net模块创建TCP服务器 laiqun@msn.cn Contents 1. 代码实现 2. 使用telnet连接服务器测试 3. 创建一个TCP的client 1. 代码实现 ; ...
- 使用nodejs的http模块创建web服务器
使用nodejs的http模块创建web服务器 laiqun@msn.cn Contents 1. web服务器基础知识 2. Node.js的Web 服务器 3. 代码实现 1. web服务器基础知 ...
- nodejs学习笔记<二> 使用node创建基础服务器
创建服务器的 server.js 内容. var http = require("http"); // 引用http模块 http.createServer(function(re ...
- nodejs的express框架创建https服务器
一 openssl创建https私钥和证书 1.下载windows版openssl: http://slproweb.com/products/Win32OpenSSL.html Win64OpenS ...
随机推荐
- 【.net 深呼吸】序列化中的“引用保留”
假设 K 类中有两个属性/字段的类型相同,并且它们引用的是同一个对象实例,在序列化的默认处理中,会为每个引用单独生成数据. 看看下面两个类. [DataContract] public class 帅 ...
- 12306官方火车票Api接口
2017,现在已进入春运期间,真的是一票难求,深有体会.各种购票抢票软件应运而生,也有购买加速包提高抢票几率,可以理解为变相的黄牛.对于技术人员,虽然写一个抢票软件还是比较难的,但是还是简单看看123 ...
- C++内存对齐总结
大家都知道,C++空类的内存大小为1字节,为了保证其对象拥有彼此独立的内存地址.非空类的大小与类中非静态成员变量和虚函数表的多少有关. 而值得注意的是,类中非静态成员变量的大小与编译器内存对齐的设置有 ...
- 在离线环境中发布.NET Core至Windows Server 2008
在离线环境中发布.NET Core至Windows Server 2008 0x00 写在开始 之前一篇博客中写了在离线环境中使用.NET Core,之后一边学习一边写了一些页面作为测试,现在打算发布 ...
- OpenCASCADE Shape Location
OpenCASCADE Shape Location eryar@163.com Abstract. The TopLoc package of OpenCASCADE gives resources ...
- C#多线程之线程池篇3
在上一篇C#多线程之线程池篇2中,我们主要学习了线程池和并行度以及如何实现取消选项的相关知识.在这一篇中,我们主要学习如何使用等待句柄和超时.使用计时器和使用BackgroundWorker组件的相关 ...
- Asp.Net 操作XML文件的增删改查 利用GridView
不废话,直接上如何利用Asp.NET操作XML文件,并对其属性进行修改,刚开始的时候,是打算使用JS来控制生成XML文件的,但是最后却是无法创建文件,读取文件则没有使用了 index.aspx 文件 ...
- 开发者最爱的Firebug停止更新和维护
近日,Firebug团队在其官网上宣布,Firebug将不再继续开发和维护,并邀请大家使用Firefox的内置开发工具. Firebug最初是2006年1月由Joe Hewitt编写, ...
- 水平可见直线 bzoj 1007
水平可见直线 (1s 128M) lines [问题描述] 在xoy直角坐标平面上有n条直线L1,L2,...Ln,若在y值为正无穷大处往下看,能见到Li的某个子线段,则称Li为可见的,否则Li为被覆 ...
- MementoPattern(备忘录模式)
/** * 备忘录模式 * @author TMAC-J * 用于存储bean的状态 */ public class MementoPattern { public class Memento{ pr ...