Http状态码
- 101 Websocket 双向通信
- 200 成功 204 没有响应体 206 断点续传
- 301(永久重定向(music.baidu.com)) 302(临时重定向(负载均衡)) 304(缓存)只能服务端设置
- 401 没有权限 403 登录了没有权限 404 405 请求方法不存在、不支持
- 502 负载均衡
请求方法(RestfulApi)
根据不同的动作 做对应的处理
- get 获取资源
- post 新增资源
- put 上传文件 修改
- delete 删除资源
- options 跨域出现 (复杂请求时出现) 只是get / post 都是简单请求 + 自定义的header
Node实现http服务
const http = require('http')
let server = http.createServer()
let querystring = require('querystring');
let url = require('url'); // url.parse
server.on('request',(req,res)=>{
/*
req 代表的是客户端
res 代表的就是服务端
req.method(大写)、req.url、req.httpVersion、req.headers(小写)
*/
let {pathname,query} = url.parse(req.url,true)
// 获取请求体
let arr = []
req.on('data',function(chunk){
// 流的原理 push(null) data方法不一定会触发
arr.push(chunk)
console.log(chunk.toString())
})
req.on('end',function(){
console.log('end') // end是一定触发
res.statusCode = 404 // 响应状态码
res.setHeader('Content-Type','text/plain;charset=utf-8')
let content = Buffer.concat(arr).toString()
let type = req.headers['content-type']
if(type === 'application/json'){
let obj = JSON.parse(content)
return res.end(obj)
}else if(type === 'application/x-www-form-urlencoded'){
let obj = querystring.parse(content)
return res.end(obj.a+'')
// let str = 'a=1&b=2'
// str.replace(/([^=&])=([^&=])/g,function(){
// console.log(arguments[1],arguments[2])
// })
}else{
return res.end(content)
}
})
})
let port = 3000;
server.listen(port,()=>{
console.log(`server start ${port}`)
})
// 端口占用
server.on('error',(err)=>{
if(err.errno==='EADDRINUSE'){
server.listen(++port)
}
})
Node实现http客户端
const http = require('http');
let config = {
port:3000,
hostname:'localhost',
headers:{
'Content-Type':'application/json'
},
method:'POST'
}
// 请求后 会将响应的结果 放到函数中
let client = http.request(config,function(res){
res.on('data',function(chunk){
console.log(chunk.toString())
})
})
client.end('aaa') // 写响应体 ajax的data数据
静态服务
const http = require("http");
const url = require("url");
const path = require("path");
const fs = require("fs").promises;
const { createReadStream } = require("fs");
const mime = require("mime");
class HttpServer{
async handleRequest(req,res){
let {pathname,query} = url.parse(req.url,true)
let filePath = path.join(__dirname,pathname)
try{
let statObj = await fs.stat(filePath)
this.sendFile(statObj,filePath,req,res)
}catch(e){
this.sendError(e,res)
}
}
async sendFile(statObj,filePath,req,res){
if(statObj.isDirectory()){
filePath = path.join(filePath,'index.html')
try{
await fs.access(filePath)
}catch(e){
return this.sendError(e,res)
}
}
res.setHeader('Content-Type',mime.getType(filePath)+";chartset=utf-8")
createReadStream(filePath).pipe(res)
}
sendError(e,res){
res.statusCode = 404;
res.end('Not Found')
}
start(...args){
let server = http.createServer(this.handleRequest.bind(this))
server.listen(...args)
}
}
let hs = new HttpServer();
hs.start(3000,()=>{
console.log('server start')
})