nodeAPI--HTTP
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:
通信:
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的更多相关文章
- Node.js学习笔记——Node.js开发Web后台服务
一.简介 Node.js 是一个基于Google Chrome V8 引擎的 JavaScript 运行环境.Node.js 使用了一个事件驱动.非阻塞式 I/O 的模型,使其轻量又高效.Node.j ...
- Node.js实现RESTful api,express or koa?
文章导读: 一.what's RESTful API 二.Express RESTful API 三.KOA RESTful API 四.express还是koa? 五.参考资料 一.what's R ...
- Node.js学习笔记(一)
1.回调函数 node是一个异步事件驱动的平台,所以在代码中我们经常需要使用回调函数. 例: setTimeout(function(){ console.log('callback is calle ...
- NodeJS入门(五)—— process对象
process对象用于处理与当前进程相关的事情,它是一个全局对象,可以在任何地方直接访问到它而无需引入额外模块. 它是 EventEmitter 的一个实例. 本章的示例可以从我的Github上下载到 ...
- NodeJS入门(四)—— path对象
很快Node就会迎来4.0的时代,届时将并入现有的iojs,所以先前写过的iojs入门系列直接更名为NodeJS入门. 本篇开始将逐个介绍Node的各主要模块,依循API文档走一遍,但会给出比API文 ...
- 利用node构建本地服务
利用node构建本地服务 首先安装下node.js,地址为https://nodejs.org/en/,然后安装npm. node.js的中文api地址http://nodeapi.ucdok.com ...
- node.js之path
说到node.js,可能实际中用到node进行后台开发的公司不多,大部分人都没有开发后台的经验.但是也要了解node相关模块的用法,因为现在前端自动化脚本的构建,模块的打包越来越离不开node.特别是 ...
- docker 会这些也够
$ sudo systemctl start docker $ sudo systemctl stop docker $ sudo systemctl restart docker If you wa ...
- Nodejs学习笔记(一)--- 简介及安装Node.js开发环境
目录 学习资料 简介 安装Node.js npm简介 开发工具 Sublime Node.js开发环境配置 扩展:安装多版本管理器 学习资料 1.深入浅出Node.js http://www.info ...
- 使用 Express 和 waterline 创建简单 Restful API
这几篇都是我原来首发在 segmentfault 上的地址:https://segmentfault.com/a/1190000004996659 突然想起来我这个博客冷落了好多年了,也该更新一下, ...
随机推荐
- zoj.3868.GCD Expectation(数学推导>>容斥原理)
GCD Expectation Time Limit: 4 Seconds Memory Limit: 262144 KB ...
- Radar Installation(贪心)
Radar Installation Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 56826 Accepted: 12 ...
- iOS文件存储路径规定
Storing Your App’s Data Efficiently https://developer.apple.com/icloud/documentation/data-storage/in ...
- [codeforces 325]B. Stadium and Games
[codeforces 325]B. Stadium and Games 试题描述 Daniel is organizing a football tournament. He has come up ...
- Android 中 设置TextView垂直滚动
布局文件 android:scrollbars="vertical" android:singleLine="false" 代码文件 ctl_tv_conten ...
- 深入了解PooledConnectionFactory CachingConnectionFactory Sin
深入理解PooledConnectionFactory CachingConnectionFactory SingleConnectionFactory PooledConnectionFactory ...
- Two Sum I & II
Two Sum I Given an array of integers, find two numbers such that they add up to a specific target nu ...
- JSON: property "xxx" has no getter method in class "..."
Exception in thread "main" net.sf.json.JSONException: java.lang.NoSuchMethodException: Pro ...
- CARP 使用笔记
1.安装 freebsd 7.3下用kldload if_carp 加载不了,报找不到模块的错,升级到9.2后就可以了. 然后按照freebsd官方手册的ifconfig carp0 create创建 ...
- Android 阅读Tasks and Back Stack文章后的重点摘抄
这篇文章是做android的必读篇目,要仔细阅读,原文连接http://developer.android.com/guide/components/tasks-and-back-stack.html ...