http模块概念
http服务器是继承自tcp服务器, http协议是应用层协议 是基于TCP的 对请求和响应进行了包装,req是可读流,res是可写流
let http = require('http')
let url = require('url')
let server = http.createServer((req, res) => {
res.end('hello node.js')
})
req
req代表请求信息
let server = http.createServer((req, res) => {
// url: http://localhost:8080/index.html?name=123 假设完整url
let { pathname, query } = url.parse(req.url, true)
console.log(pathname) // /index.html
console.log(query) // {name: 123}
console.log(req.url) // /index.html?name=123
console.log(req.headers) //获取请求头
})
res
res代表响应信息
let server = http.createServer((req, res) => {
// res.setHeader('Content-Type', 'text/html;charset=utf8')
res.writeHead(200, { // writeHead: 一旦调用会立刻向客户端发送
'Content-Type': 'text/html;charset=utf8'
})
res.statusCode = 400
res.end()
})
http和tcp服务器的关系
req, res都是从socket来的,先监听socket的data事件,然后等事件发生的时候,进行解析 解析出请求头,在创建请求对象,再根据请求对象创建响应对象
http做客户端
get请求
const http = require('http')
const options = {
host: 'localhost',
port: 8080,
method: 'get',
path: '/post'
}
let req = http.request(options)
// 当服务器把请求体发回来的时候,或者说客户端接受到响应的时候
req.on('response', (res) => {
let result = []
res.on('data', (data) => {
result.push(data)
})
res.on('end', () => {
let str = Buffer.concat(result)
console.log(str.toString())
})
})
//只有调用end()才会真正向服务器发请求
req.end()
对应服务器代码
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json()) // 处理json的请求体
app.get('/post', (req, res, next) => {
// console.log(req.body)
console.log(123)
res.send('123')
})
app.listen(8080)
post请求
let http = require('http')
let options = {
host: 'localhost',
port: 8080,
method: 'POST',
path: '/post',
headers: {
'Content-Type': 'application/json'
}
}
let req = http.request(options) //请求并没发出
// 当服务器把请求体发回来的时候,或者说客户端接受到响应的时候
req.on('response', (res) => {
let result = []
res.on('data', (data) => {
result.push(data)
})
res.on('end', (data) => {
let str = Buffer.concat(result)
console.log(str.toString())
})
})
// 向请求体写数据
req.write('{"name": "zfpx"}')
// 是结束写入请求体,只有调用end()才会真正向服务器发请求
req.end()
对应服务器代码
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json()) // 处理json的请求体
app.post('/post', (req, res, next) => {
// console.log(req.body)
res.send('123')
})
app.listen(8080)