1. 程式人生 > 其它 >nodejs使用http模組寫web的request和 response

nodejs使用http模組寫web的request和 response

一.request 物件

  • request 物件型別 <http.IncomingMessage>, 繼承自stream.Readable

  • request 物件常用成員

    • request.headers

    • request.rawHeaders

    • request.httpVersion

    • request.method

    • request.url

二.response 物件

  • response 物件型別 <http.ServerResponse>

  • response 物件常用成員

    • response.writeHead(statusCode[, statusMessage][, headers])

      1. This method must only be called once on a message and it must be called before response.end() is called.

      • 這個方法在每次請求響應前都必須被呼叫(只能呼叫一次)。並且必須在end()方法呼叫前呼叫

2. If you call response.write() or response.end() before calling this, 
the implicit/mutable headers will be calculated and call this function for you. - 如果在呼叫writeHead()方法之前呼叫了write() 或 end()方法,系統會自動幫你呼叫writeHead()方法,並且會生成預設的響應頭

 

 

3. When headers have been set with response.setHeader(), they will be merged with any headers passed to response.writeHead(),
with the headers passed to response.writeHead() given precedence. - 如果通過 res.setHeader() 也設定了響應頭,那麼系統會將serHeader()設定的響應頭和writeHead()設定的響應頭合併。 並且writeHead()的設定優先

 

// 示例程式碼:
res.writeHead(200, 'OK', { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(msg) });

 

  • response.write(chunk[, encoding][, callback])

    • 引數1:要寫入的資料,可以是字串或二進位制資料,必填

    • 引數2:編碼,預設是utf8,選填。

    • 引數3:回撥函式,選填。

  • response.end([data][, encoding][, callback])

    • 結束響應。

    • This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.

    • res.end()這個方法告訴伺服器所有要傳送的響應頭和響應體都發送完畢了。可以人為這次響應結束了。

    • 同時每次響應都必須呼叫該方法,用來結束響應

* 引數1:結束響應前要傳送的資料,選填。
* 引數2:編碼,選填。
* 引數3:回撥函式,選填。
  • response.setHeader(name, value)

    • 設定響應報文頭

  • response.statusCode

    • 設定或讀取http響應碼

  • response.statusMessage

    • 設定或讀取http響應狀態訊息

 

總結:

  demo1

wirtehead(200, "ok", {'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(msg)})

  demo2

response.statusCode(200)
response.statusMessage('ok')
response.setHeader('Content-Type', 'text/html; charset=utf-8')
response.setHeader('Content-Length', Buffer.byteLength(msg))

  demo和demo2的效果是一樣的,並且demo1的優先順序更高,推薦demo1的用法。