原生node处理get和post请求

时间:2022-07-26
本文章向大家介绍原生node处理get和post请求,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
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(8888);