HTTP(hypertext transport protocol)协议也叫超文本传输协议,是一种基于 TCP/IP 的应用层通信协议,这个协议详细规定了浏览器和万维网服务器之间互相通信的规则。
协议主要规定了两方面的内容
- 客户端向服务器发送数据,称之为请求报文
- 服务器向客户端返回数据,称之为响应报文
HTTP 请求报文包括四部分
HTTP 响应报文也包括四个部分
使用 nodejs 创建 HTTP 服务器
var http = require('http');
var server = http.createServer(function(request, response){
response.end('hello world!!');
});
server.listen(8000);
- request 是对请求报文的封装对象
- response 是对响应的封装对象
获取请求
console.log(request.method);
console.log(request.httpVersion);
console.log(request.url);
console.log(request.headers);
request.on('data', function(chunk){})
request.on('end', function(){});
设置响应
response.statusCode = 200;
response.setHeader('content-type','text/html;charset-utf-8');
response.write('body');
response.end();
#### 创建http服务
```javascript
const http = require('http');
const ws = http.createServer(function(request,response){
response.end('hello 你好');
})
ws.listen(80,function(){
console.log('服务启动,端口8000监听中');
})
获取请求信息
const http = require('http');
const url = require('url');
const ws = http.createServer((request,response)=>{
console.log(url.parse(request.url).pathname);
console.log(url.parse(request.url,true).query);
console.log(request.headers);
response.end('hello');
})
ws.listen(8001,()=>{
console.log('端口监听ing');
})
const http = require('http');
const ps = require('querystring');
const ws = http.createServer((request,response)=>{
let body = '';
request.on('data',chunk=>{
body += chunk.toString();
})
request.on('end',()=>{
console.log(body);
console.log( ps.parse(body));
response.end('body server1');
})
})
ws.listen(80,()=>{
});
获取响应信息
/ 引入http模块
const http = require('http');
const url = require('url');
const fs = require('fs');
const ws = http.createServer((request,response)=>{
let pathname = url.parse(request.url,true).pathname;
let directory = __dirname +'public';
let pathName = directory + pathname;
fs.readFile(pathName,(err,data)=>{
if(err) {
response.end('404 Not Found');
} else {
response.end(data);
}
})
})
ws.listen(80);
|