HTTP:   //超文本协议,是属于TCP上层的协议

  • http协议构建在请求和响应概念上,node.js中对应http.ServerRequest,http.ServerResponse;
  • 当用户浏览网站,用户代理(浏览器)会创建一个请求,该请求通过TCP发送给web服务器;

流对接:

var http = require('http');
var fs = require('fs');
var stream; http.createServer(function (req, res) {
res.writeHead(200,{'Content-Type':'image/png'});
stream = fs.createReadStream('1.png');
stream.on('data', function(data) {
res.write(data);
});
stream.on('end', function() {
res.end();
});
}).listen(3000);
--------------------------------------------
require('http').createServer(function (req, res) {
res.writeHead(200,{'Content-Type':'image/png'});
require('fs').createReadStream('1.png').pipe(res);
}).listen(3000);

一个简单web服务器的例子:

  • querystring模块:它能将一个字符串解析成一个对象;
require('querystring').parse('name = guillermo');
//{"name":"guillermo"}
  • url和method判断,headers :req.url ; req.method //返回的是大写; req.headers //返回的是数组
  • data和end事件
var http = require('http');
var qs = require('querystring');
http.createServer(function(req, res) {
if('/' === req.url) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end([
'<form method="post" action="/url">',
'<h1>My form</h1>',
'<fieldset>',
'<label>Personal information</label>',
'<p>What is your name?</p>',
'<input type = "text" name = "name">',
'<p><button>Submit</button></p>',
'</form>'
].join(''));
} else if('/url' === req.url && 'POST' === req.method) {
var body = '';
req.on('data', function(chunk) {
body += chunk;
});
req.on('end', function() {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<p>Your name is <b>' + qs.parse(body).name + '</b></p>');
});
} else {
res.writeHead(404);
res.end('Not Found');
}
}).listen(3000);

client和server通信:

  • 简单例子:

    • server:

      var http = require('http');
      var qs = require('querystring');
      http.createServer(function(req, res) {
      res.writeHead(200);
      res.end('Hello World');
      }).listen(3000);
    • client:
      var http = require('http');
      http.request({ //初始化一个http.Client Request对象
      host: '127.0.0.1',
      port: 3000,
      url: '/',
      method: 'get'
      }, function(res) {
      var body = '';
      res.setEncoding('utf8');
      res.on('data', function(chunk) {
      body += chunk;
      });
      res.on('end', function() {
      console.log('\r\n We got: \033[96m' + body + '\033[39m\r\n');
      });
      }).end();
  • 通信:

    • server:

      var qs = require('querystring');
      var http = require('http');
      http.createServer(function(req, res) {
      var body = '';
      req.on('data', function(chunk) {
      body += chunk;
      });
      req.on('end', function() {
      res.writeHead(200);
      res.end('Done');
      console.log('\n got name \033[90m' + qs.parse(body).name + '\033[39m\r\n');
      });
      }).listen(3000);
    • client:

      var http = require('http');
      var qs = require('querystring'); function send(theName) {
      http.request({
      host: '127.0.0.1',
      port: 3000,
      url: '/',
      method: 'POST'
      }, function(res) {
      res.setEncoding('utf8');
      console.log('\r\n \033[90m request complete!\033[39m');
      process.stdout.write('\r\n your name: ') }).end(qs.stringify({name: theName}));
      }
      process.stdout.write('\r\n your name: ');
      process.stdin.resume();
      process.stdin.setEncoding('utf-8');
      process.stdin.on('data', function(name) {
      send(name.replace('\r\n',''));
      });

        

nodeAPI--HTTP的更多相关文章

  1. Node.js学习笔记——Node.js开发Web后台服务

    一.简介 Node.js 是一个基于Google Chrome V8 引擎的 JavaScript 运行环境.Node.js 使用了一个事件驱动.非阻塞式 I/O 的模型,使其轻量又高效.Node.j ...

  2. Node.js实现RESTful api,express or koa?

    文章导读: 一.what's RESTful API 二.Express RESTful API 三.KOA RESTful API 四.express还是koa? 五.参考资料 一.what's R ...

  3. Node.js学习笔记(一)

    1.回调函数 node是一个异步事件驱动的平台,所以在代码中我们经常需要使用回调函数. 例: setTimeout(function(){ console.log('callback is calle ...

  4. NodeJS入门(五)—— process对象

    process对象用于处理与当前进程相关的事情,它是一个全局对象,可以在任何地方直接访问到它而无需引入额外模块. 它是 EventEmitter 的一个实例. 本章的示例可以从我的Github上下载到 ...

  5. NodeJS入门(四)—— path对象

    很快Node就会迎来4.0的时代,届时将并入现有的iojs,所以先前写过的iojs入门系列直接更名为NodeJS入门. 本篇开始将逐个介绍Node的各主要模块,依循API文档走一遍,但会给出比API文 ...

  6. 利用node构建本地服务

    利用node构建本地服务 首先安装下node.js,地址为https://nodejs.org/en/,然后安装npm. node.js的中文api地址http://nodeapi.ucdok.com ...

  7. node.js之path

    说到node.js,可能实际中用到node进行后台开发的公司不多,大部分人都没有开发后台的经验.但是也要了解node相关模块的用法,因为现在前端自动化脚本的构建,模块的打包越来越离不开node.特别是 ...

  8. docker 会这些也够

    $ sudo systemctl start docker $ sudo systemctl stop docker $ sudo systemctl restart docker If you wa ...

  9. Nodejs学习笔记(一)--- 简介及安装Node.js开发环境

    目录 学习资料 简介 安装Node.js npm简介 开发工具 Sublime Node.js开发环境配置 扩展:安装多版本管理器 学习资料 1.深入浅出Node.js http://www.info ...

  10. 使用 Express 和 waterline 创建简单 Restful API

    这几篇都是我原来首发在 segmentfault 上的地址:https://segmentfault.com/a/1190000004996659  突然想起来我这个博客冷落了好多年了,也该更新一下, ...

随机推荐

  1. kindle paperwhite折腾记

    在亚马逊官网上买了一个kindle paperwhite 一代(849元) , 打算再买个皮套, 淘宝店  http://detail.tmall.com/item.htm?spm=a230r.1.1 ...

  2. chrome 调试基本信息学习

    学习链接: remote-debugging-port相关: http://blog.chromium.org/2011/05/remote-debugging-with-chrome-develop ...

  3. Radar Installation(贪心)

    Radar Installation Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 56826   Accepted: 12 ...

  4. Win 7 下制作 mac 系统启动U盘

    Win 7 下制作 mac 系统启动U盘 前几天因为工作需要,在mac 上安装了win7.后来因为习惯问题将win7 分区了,后来就是进不去mac os,只能进入win7 .可恶. 苹果客服说只能用m ...

  5. CentOS 7安装Splunk

    导读 Splunk是探索和搜索数据的最有力工具,从收集和分析应用程序.Web服务器.数据库和服务器平台的实时可视化海量数据流,分析出IT企业产生的海量数据,安全系统或任何商业应用,给你一个总的见解获得 ...

  6. 发现Select等注入语句自动跳转Code

    CODE区域: <?php $str = $_GET["keyword"]; $str00 = strtolower($str); //strtolower 变为小写函数 $ ...

  7. How to Configure Nginx for Optimized Performance

    Features Pricing Add-ons Resources | Log in Sign up   Guides & Tutorials Web Server Guides Nginx ...

  8. i++和++i的深入理解

    研究了很久,对这个一直很模糊.相信大家,看完这篇文章,会有更深一层的认识! 一直以来,++ --语法浪费了太多人的时间.说句实在话,++ -- 在C语言中其实是一个很细节的语法,除了表达简练外,真的没 ...

  9. VMware Snapshot 工作原理

    VMware中的快照是对VMDK在某个时间点的“拷贝”,这个“拷贝”并不是对VMDK文件的复制,而是保持磁盘文件和系统内存在该时间点的状态,以便在出现故障后虚拟机能够恢复到该时间点.如果对某个虚拟机创 ...

  10. Bulls and Cows

    You are playing the following Bulls and Cows game with your friend: You write down a number and ask ...