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. TableInputFormat分片及分片数据读取源码级分析

    我们在MapReduce中TextInputFormat分片和读取分片数据源码级分析 这篇中以TextInputFormat为例讲解了InputFormat的分片过程以及RecordReader读取分 ...

  2. 安卓(Android)手机如何安装APK?

    我大天朝的安卓手机只能在一个被阉割的APP市场里玩耍,有些APP可能需要直接安装APK文件.APK 是 Android Package (安卓安装包)安卓手机如何安装APK呢? 在电脑上下载安装APK ...

  3. thinkphp中模块和操作映射

    模板和操作映射功能是3.1.2版本支持的对模块和操作设置的映射机制,由于可以通过改变配置动态改变(实际真正改变,并非别名)URL访问地址,加强了应用的安全性,而且,映射机制具有URL不区分大小写访问的 ...

  4. 十条nmap常用的扫描命令

    NMap也就是Network Mapper,nmap是在网络安全渗透测试中经常会用到的强大的扫描器,功能之强大,不言而喻.下面介绍一下它的几种扫描命令.具体的还是得靠大家自己学习,因为实在太强大了. ...

  5. Item 表单页面的 Select2 相关业务逻辑

    Select2 插件官网:https://select2.github.io/ Select2 初始化说明: 代码在 public/javascripts/subchannel_items.js 中的 ...

  6. svn报错 400 Bad Request

    MyEclipse中的svn,commit经常报错 Error: Commit failed (details follow):  Error: At least one property chang ...

  7. C#开发实例 鼠标篇

    鼠标的操作控制: 鼠标是计算机的一个重要组成部分,有很多默认的设置,如双击时间间隔,闪烁频率,移动速度等,本篇使用C#获取这些基本的信息. 1.1获取鼠标信息 ①实例001 获取鼠标双击时间间隔 主要 ...

  8. SVN安装与配置 SVN整合MyEclipse

    SVN安装: 1.安装服务器 ######### 安装文件:SVN服务器############### # http://www.collab.net/downloads/subversion # C ...

  9. hping3命令

    hping3命令 网络测试 hping是用于生成和解析TCPIP协议数据包的开源工具.创作者是Salvatore Sanfilippo.目前最新版是hping3,支持使用tcl脚本自动化地调用其API ...

  10. 字符编码浅识:关于Unicode与UTF-8

    参考自阮一峰博客:http://www.ruanyifeng.com/blog/2007/10/ascii_unicode_and_utf-8.html Unicode只是一个符号集,它只规定了符号的 ...