1、http-get

  1. const http = require('http');
  2. const querystring = require('querystring')
  3. const server = http.createServer((req,res)=>{
  4. const url = req.url;
  5. req.query = querystring.parse(url.split('?')[1])
  6. res.end(
  7. JSON.stringify(req.query)
  8. )
  9. })
  10. server.listen(8000,()=>{
  11. console.log('server is linstening at 8000 port')
  12. })
  13. //NODE控制台返回结果:
  14. // GET
  15. // url: /api/get?user=weibin&age=18
  16. // query: { user: 'weibin', age: '18' }
  17. // GET
  18. // url: /favicon.ico
  19. // query: {}

2、http-post

  1. //使用POSTMAN 模拟请求 选择POST方式 填写JSON 访问http://localhost:8100
  2. const http = require('http')
  3. const server = http.createServer((req,res)=>{
  4. if(req.method === 'POST') {
  5. console.log('req content-type',req.headers['content-type']) //JSON
  6. let postData = ''
  7. // 一点一点接受数据 然后拼接起来
  8. req.on('data',chunk=>{
  9. console.log('first', chunk.toString());
  10. postData += chunk.toString()
  11. })
  12. // 接受完毕触发req的END
  13. req.on('end',()=>{
  14. console.log('postData: ' + postData)
  15. res.end('hello world')
  16. })
  17. }
  18. })
  19. server.listen(8100,()=>{
  20. console.log('server is linstening at 8100 port')
  21. })

3、get、post整合

  1. const http = require('http')
  2. const querystring = require('querystring')
  3. const server = http.createServer((req, res) => {
  4. const method = req.method;
  5. const url = req.url
  6. const path = url.split('?')[0]
  7. const query = querystring.parse(url.split('?')[1])
  8. //设置返回格式为JSON
  9. res.setHeader('Content-type', 'application/json')
  10. //返回数据
  11. const resData = {
  12. method,
  13. url,
  14. path,
  15. query
  16. }
  17. //返回结果
  18. if (method === 'GET') {
  19. res.end(JSON.stringify(resData))
  20. }
  21. if (method === 'POST') {
  22. let postData = ''
  23. // 一点一点接受数据 然后拼接起来
  24. req.on('data', chunk => {
  25. postData += chunk.toString()
  26. })
  27. // 接受完毕触发req的END
  28. req.on('end', () => {
  29. resData.postData = postData
  30. res.end(JSON.stringify(resData))
  31. })
  32. }
  33. })
  34. server.listen(8000, () => {
  35. console.log('server is linstening at 8000 port')
  36. })