1.从输入url到页面显示的过程 2.nodejs处理http请求 3.nodejs处理get请求 4.nodejs处理post请求 5.综合演练
1.从输入url到显示页面的过程?
DNS解析,建立TCP连接,发送http请求server 接收http请求,处理,并返回客户端接受到返回数据,处理数据(如渲染页面,执行js)
2.nodejs 处理 http 请求
- get请求和querystring - post请求和postdata - 路由
简单示例
const http
= require('http')
const server
= http
.createServer((req
,res
) => {
res
.end('hello world')
})
server
.listen(3000)
3.nodejs 处理 get 请求
get请求,即客户端要向 server 端获取数据,如查询博客列表通过querystring 来传递数据,如a.html?a=100&b=200浏览器直接访问,就发送 get 请求
const http
= require('http')
const querystring
= require('querystring')
const server
= http
.createServer((req
,res
) => {
console
.log(req
.method
)
const url
= req
.url
req
.query
= querystring
.parse(url
.split('?')[1])
res
.end(JSON.stringify(req
.query
))
})
server
.listen(3000)
1.需要querystring模块 2.req.url获取 url 3.req.method 获取请求方式 get/post 3.通过JSON.stringfy()返回的是JSON字符串。
4.nodejs 处理 post 请求
post请求,即客户端要向服务器端传递数据,如新建博客通过post data 传递数据浏览器无法直接模拟,用postman演示
const http
= require('http')
const server
= http
.createServer((req
,res
) => {
console
.log('content-type',req
.headers
['content-type'])
let postData
= ""
req
.on('data', chunk
=> {
postData
+= chunk
.toString()
})
req
.on('end', () => {
console
.log(postData
)
res
.end('hello world')
})
})
1.req.headers获取请求头信息 2.监听 data 事件获取数据 3.监听 end 事件结束 控制台输出:
content
-type application
/json
{
"username": "admin",
"password": "123456"
}
5.综合演练
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])
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(3000)