微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

丁鹿学堂:原生nodejs简单实现http响应

nodeJS处理get请求

get请求是前端要像后端去索取一些内容的时候使用的。
querystring是node内置的方法,通过它可以很方便处理前端get请求携带的参数。

const http = require('http')
const querystring = require('querystring')
const server = http.createServer((req,res)=>{
   const url = req.url
   req.query = querystring.parse(url.split('?')[1])
   res.end(JSON.stringify(req.query))
})
server.listen(3000)
console.log('server run ...');
nodeJS处理post请求

post请求,是前端要像服务端传递数据。如注册用户登录

const server = http.createServer((req,res)=>{
   if(req.method === 'POST'){
      // 接收数据
      let postData = ''
      req.on('data',chunk=>{
         postData += chunk.toString()
      })
      req.on('end',data=>{
         console.log(postData); // 接受到数据
         res.end('done')
      })
   }
})
服务端路由

路由就是url路径,代表了url资源的唯一的标识。
在node 中,通过req.url获取到的数据,url.split(‘?’)[1]) 获取的是参数,[0]获取的就是路由。

综合的一个小案例:

麻雀虽小,五脏俱全

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(req.method === 'POST'){
      // 接收数据
      let postData = ''
      req.on('data',chunk=>{
         postData += chunk.toString()
      })
      req.on('end',data=>{
         resData.postData = postData
         res.end(JSON.stringify(resData))
      })
   }
})
server.listen(3000)
console.log('server run ...');

原文地址:https://www.jb51.cc/wenti/3280899.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐