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 ...
随机推荐
- ASP.NET Core HTTP 管道中的那些事儿
前言 马上2016年就要过去了,时间可是真快啊. 上次写完 Identity 系列之后,反响还不错,所以本来打算写一个 ASP.NET Core 中间件系列的,但是中间遇到了很多事情.首先是 NPOI ...
- BIOS中未启用虚拟化支持系列~~例如:因此无法安装Hyper-V
异常处理汇总-服务器系列:http://www.cnblogs.com/dunitian/p/4522983.html 一般都是启动一下CUP虚拟化就可以了 比如华硕的:
- EventBus实现activity跟fragment交互数据
最近老是听到技术群里面有人提出需求,activity跟fragment交互数据,或者从一个activity跳转到另外一个activity的fragment,所以我给大家介绍一个开源项目,EventBu ...
- LeetCode[3] Longest Substring Without Repeating Characters
题目描述 Given a string, find the length of the longest substring without repeating characters. For exam ...
- .net 分布式架构之分布式缓存中间件
开源git地址: http://git.oschina.net/chejiangyi/XXF.BaseService.DistributedCache 分布式缓存中间件 方便实现缓存的分布式,集群, ...
- ASP.NET WebApi OWIN 实现 OAuth 2.0
OAuth(开放授权)是一个开放标准,允许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用. OAuth 允许用户提供一个令牌, ...
- 深入浅出JavaScript之原型链&继承
Javascript语言的继承机制,它没有"子类"和"父类"的概念,也没有"类"(class)和"实例"(instanc ...
- Android开发学习—— Fragment
#Fragment* 用途:在一个Activity里切换界面,切换界面时只切换Fragment里面的内容* 生命周期方法跟Activity一致,可以理解把其为就是一个Activity* 定义布局文件作 ...
- Configure a bridged network interface for KVM using RHEL 5.4 or later?
environment Red Hat Enterprise Linux 5.4 or later Red Hat Enterprise Linux 6.0 or later KVM virtual ...
- linux上使用google身份验证器(简版)
系统:centos6.6 下载google身份验证包google-authenticator-master(其实只是一个.zip文件,在windwos下解压,然后传进linux) #cd /data/ ...