Node JS handles GET and POST requests of http requests

一、http

  1. http The summary of the request is as follows:
  • DNSParsing, establishing TCPconnections, sending httprequest
  • serverReceiving the httprequest, the processing, and returns
  • The client receives the returned data, processes the data, such as rendering the page, and executing JS
  1. node JSProcessing httpthe request, as follows:
  • get Request and querystring
  • post Request and postdata
  • routing

Two, node JS processes get requests

  1. node JSProcessing getthe request, as follows:
  • getRequest that the client would like serverclients to obtain data such as query list
  • By querystringtransmitting data, such asa.html?a=100&b=200
  • Direct access to the browser, it sends a getrequest
  1. By npm init -yinitializing the project, create a new app.jsfile, the code is as follows:
const http = require('http')
const querystring = require('querystring')

const server = http.createServer((req, res) => {
    
    
  console.log('method:', req.method)
  const url = req.url
  console.log('url:', url)
  req.query = querystring.parse(url.split('?')[1])
  console.log('query:',req.query)
  res.end(JSON.stringify(req.query)) 
})

server.listen(8000)
console.log('ok')
  1. By the node app.jscommand execution program, are input in the browser window http://localhost:8000/api/listand http://localhost:8000/api/list?name=zhangsan&age=20sending GETthe request, as follows:
  • http://localhost:8000/api/list,as the picture shows:

Insert picture description here
Insert picture description here

  • http://localhost:8000/api/list?name=zhangsan&age=20,as the picture shows:

Insert picture description here
Insert picture description here

Three, node JS processes post requests

  1. node JSProcessing postthe request, as follows:
  • post Request, that is, the client must pass data like the server, such as new information
  • By post.datatransmitting data
  • The browser cannot simulate directly, you need to write by hand js, or usepostman
  1. In the app.jsdocument, the code is as follows:
const http = require('http')
const querystring = require('querystring')

const server = http.createServer((req,res) => {
    
    
  if (req.method === 'POST') {
    
    
    // req 数据格式
    console.log('req content-type:', req.headers['content-type'])
    // 接收数据
    let postData = ''
    req.on('data', chunk => {
    
    
      postData += chunk.toString()
    })
    req.on('end', () => {
    
    
      console.log('postData:', postData)
      res.end('end 结束')
    })
  }
})


server.listen(8000)
console.log('ok')
  1. By node app.jscommand program running in postman, the http://localhost:8000/request in rawthe input { "name": "zhangsan", "age": 24 }transmission POSTrequest, as shown below:

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_42614080/article/details/110734309