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. 繁华模拟赛 David与Vincent的博弈游戏

    #include<iostream> #include<cstdio> #include<string> #include<cstring> #incl ...

  2. tyvj4221 货车漂移

    背景 蒟蒻中学的蒟蒻遇到了一些小问题. 描述 蒟蒻考完noip也就要回家种田了,他老家的田地在s点,可是种子市场在e点,为了购买种子,中途要经过很多城市,这导致快递费非常的贵(因为快到双11了),于是 ...

  3. Tautology(structure)

    Tautology Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 10061   Accepted: 3826 Descri ...

  4. HDU 2577 How to Type(dp题)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2577 解题报告:有一个长度在100以内的字符串,并且这个字符串只有大写和小写字母组成,现在要把这些字符 ...

  5. [Effective JavaScript 笔记]第52条:数组字面量优于数组构造函数

    js的优雅很大程序要归功于程序中常见的构造块(Object,Function及Array)的简明的字面量语法.字面量是一种表示数组的优雅方法. var a=[1,2,3,5,7,8]; 也可以使用构造 ...

  6. jsp&servlet学习笔记

    1.路径引用问题 一个css.jsp.html.或者javascript文件从从一个工程复制到另一工程,如果引用的时候使用的时相对路径,看似没有错误,但是却一直引用不进来,这时候要使用绝对路径,这样才 ...

  7. NSArray和NSMutableArray

    //1. NSArray EOItems *eOItems = [[EOItems alloc] init]; eOItems.ID = [NSNumber numberWithInt:]; NSAr ...

  8. python 之验证码

    验证码原理在于后台自动创建一张带有随机内容的图片,然后将内容通过img标签输出到页面. 安装图像处理模块: pip3 install pillow

  9. Python获取目录、文件的注意事项

    Python获取指定路径下的子目录和文件有两种方法: os.listdir(dir)和os.walk(dir),前者列出dir目录下的所有直接子目录和文件的名称(均不包含完整路径),如 >> ...

  10. 使用豆瓣的pypi源

    配置文件位置: 1.linux ~/.pip/pip.conf 2.windows %HOME%\pip\pip.ini 配置文件内容:[global] index-url = http://pypi ...