Node.js build HTTP service

Node in HTTP module

  • TCP and UDP are part of a network transport protocol, if you want to use and efficient network architecture, should start from the transport layer, but for the classic web browser and server-side communication scenario, if the mere use of a more underlying transport protocol will become trouble.
  • So for the classical B (browser) S (server) communications, based on a transport layer protocol specially formulated are more on: HTTP, a browser and server communicate, because the HTTP protocol itself does not consider the data how to transfer and other details, it is an application-layer protocol.
  • Node provides a packaging means for HTTP and HTTPS based HTPP and HTTPS.
count http = require('http')
const server = http.createServer()

server instance

API:

  • event: close, triggered when the service shuts down
  • event: reques, triggering request message is received
  • event: close (), close the service
  • event: listening, getting state of service

Request Object

API:

  • request.method, request method
  • request.url, the request path
  • request.headers, request header
  • request.httpVersion, request http protocol version

Response Object

API:

  • response.end (), end response
  • response.setHeader (name, value), in response to the first set
  • response.removeHeader (name, value), delete the response header
  • response.statusCode, provided the response status code
  • response.statusMessage, provided the response status code
  • response.write (), write the response data
  • response.writeHead (), in response to the write head

Example:

const http = require('http')

const hostname = '127.0.0.1'
const port = '20000'

const server = http.createServer((req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.end('Hello World\n')
})

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}`)
})

html:

const http = require('http')

const hostname = '127.0.0.1'
const port = '20001'

const server = http.createServer((req, res) => {
  // 响应文本类型的html,响应格式 utf-8
  res.setHeader('Content-Type', 'text/html; charset=utf-8')
  res.end(`<h1>hello你好,世界</h1>`)
})

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`)
})

Guess you like

Origin www.cnblogs.com/liea/p/11832573.html