根據不一樣的動做 作對應的處理html
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)
}
})
複製代碼
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')
})
複製代碼