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 ...
随机推荐
- Connect() 2016 大会的主题 ---微软大法好
文章首发于微信公众号"dotnet跨平台",欢迎关注,可以扫页面左面的二维码. 今年 Connect 大会的主题是 Big possibilities. Bold technolo ...
- Bootstrap 模态框(Modal)插件
页面效果: html+js: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...
- python黑魔法 -- 内置方法使用
很多pythonic的代码都会用到内置方法,根据自己的经验,罗列一下自己知道的内置方法. __getitem__ __setitem__ __delitem__ 这三个方法是字典类的内置方法,分别对应 ...
- Android性能优化之巧用软引用与弱引用优化内存使用
前言: 从事Android开发的同学都知道移动设备的内存使用是非常敏感的话题,今天我们来看下如何使用软引用与弱引用来优化内存使用.下面来理解几个概念. 1.StrongReference(强引用) 强 ...
- java单向加密算法小结(1)--Base64算法
从这一篇起整理一下常见的加密算法以及在java中使用的demo,首先从最简单的开始. 简单了解 Base64严格来说并不是一种加密算法,而是一种编码/解码的实现方式. 我们都知道,数据在计算机网络之间 ...
- Android 工具-adb
Android 工具-adb 版权声明:本文为博主原创文章,未经博主允许不得转载. Android 开发中, adb 是开发者经常使用的工具,是 Android 开发者必须掌握的. Android D ...
- 分享一个php的启动关闭脚本(原)
自己简单写的一个php服务的启动脚本和大家分享 思路(实现的原理): 1:function模块+case语句多分支判断 2:通过添加# chkconfig: 2345 43 89注释实现开机自启动(前 ...
- could not initialize proxy - no Session
这是一个精典的问题:因为我们在hibernate里面load一个对象出来时,用到的是代理对象,也就是说当我们在执行load方法时并没有发sql语句,而是返回一个proxy对象.只有当们具体用到哪个ge ...
- Mono+Jexus让C#运行在Linux(centos7_x64),学习笔记
.h2cls { background: #6fa833 none repeat scroll 0 0 !important; color: #fff; font-family: "微软雅黑 ...
- Angular2笔记:NgModule
Angular的模块的目的是用来组织app的逻辑结构. 在ng中使用@NgModule修饰的class就被认为是一个ng module.NgModule可以管理模块内部的Components.Dire ...