HTTP-概述
从输入url到显示页面的整个过程
- DNS解析,建立TCP连接,发送http请求 浏览器输入地址,首先进行DNS解析(url只是域名,需要通过DNS解析,获取ip地址对应的服务器),客户端和服务器建立TCP连接(三次握手),成功后发送http请求
- server接收到http请求,处理,并返回
- 客户端接收数据,处理数据(如渲染页面,执行js)
处理get请求
- get请求和querystring
- post请求和postdata
- 路由
- get请求,即客户端要向server端获取数据,如查询博客列表
- 通过querystring来传递数据,如 a.html?a=100&b=200
- 浏览器直接访问,就发送get请求 DEMO
这里要注意:
- res.end()必须返回字符串格式
- query是从url获取,原格式是:author=zhangsan&keyword=teemo,使用querystring.parse,格式为{ author: 'zhangsan', keyword: 'teemo' }
const http = require('http');
const querystring = require('querystring');
const server = http.createServer((req,res) => {
let method = req.method;
let url = req.url;
let query = querystring.parse(url.split('?')[1]);
res.end(
JSON.stringify({
method,
url,
query
})
)
})
server.listen('1111');
返回:
{"method":"GET","url":"/?author=zhangsan&keyword=teemo","query":{"author":"zhangsan","keyword":"teemo"}}
处理post请求
- post请求,即客户端要向服务端传递数据,如新建博客
- 通过post data传递数据
- 浏览器无法直接模拟,需要手写js,或者使用postman DEMO
const http = require('http');
const server = http.createServer((req,res) => {
if(req.method === 'POST') {
// req 数据格式
console.log('req content-type:', req.headers['content-type']);
// 接受数据
let postData = '';
req.on('data', chunk => {
console.log('chunk数据:',chunk);
postData += chunk.toString();
});
req.on('end', () => {
console.log('postData:', postData);
res.end('hello world');
});
}
})
server.listen('1111');
处理http请求的综合实例
const http = require('http');
const querystring = require('querystring');
const server = http.createServer((req,res) => {
const method = req.method;
const url = req.url;
const path = url.split('?')[0];
const query = querystring.parse(url.split('?')[1]);
// 设置返回格式为 JSON
res.setHeader('Content-type', 'application/json');
// 返回的数据
const resData = {
method,
url,
path,
query
}
// 返回
if(method === 'GET') {
res.end(JSON.stringify(resData))
};
if(method === 'POST') {
let postData = '';
req.on('data', chunk => {
postData += chunk.toString();
});
req.on('end', () => {
resData.postData = postData;
res.end(JSON.stringify(resData));
});
};
})
server.listen('1111');