- Mastering Node.js(Second Edition)
- Sandro Pasquali Kevin Faaborg
- 317字
- 2021-07-02 19:28:51
Working with headers
Each HTTP request made to a Node server will likely contain useful header information, and clients normally expect to receive similar package information from a server. Node provides straightforward interfaces for reading and writing headers. We'll briefly go over those simple interfaces, clarifying some details. Finally, we'll discuss how more advanced header usage might be implemented in Node, studying some common network responsibilities a Node server will likely need to accommodate.
A typical request header will look something like the following:

Headers are simple key/value pairs. Request keys are always lowercased. You may use any case format when setting response keys.
Reading headers is straightforward. Read header information by examining the request.header object, which is a 1:1 mapping of the header's key/value pairs. To fetch the accept header from the previous example, simply read request.headers.accept.
The number of incoming headers can be limited by setting the maxHeadersCount property of your HTTP server.
If it is preferred that headers are read programmatically, Node provides the response.getHeader method, accepting the header key as its first argument.
While request headers are simple key/value pairs, when writing headers, we need a more expressive interface. As a response typically must send a status code, Node provides a straightforward way to prepare a response status line and header group in one command:
response.writeHead(200, {
'Content-Length': 4096,
'Content-Type': 'text/plain'
});
To set headers inpidually, you can use response.setHeader, passing two arguments: the header key, followed by the header value.
To set multiple headers with the same name, you may pass an array to response.setHeader:
response.setHeader("Set-Cookie", ["session:12345", "language=en"]);
Occasionally, it may be necessary to remove a response header after that header has been queued. This is accomplished using response.removeHeader, passing the header name to be removed as an argument.
Headers must be written prior to writing a response. It is an error to write a header after a response has been sent.
- 網(wǎng)絡(luò)教育學(xué)習(xí)指導(dǎo)
- 物聯(lián)網(wǎng)短距離無(wú)線通信技術(shù)應(yīng)用與開發(fā)
- 物聯(lián)網(wǎng)網(wǎng)絡(luò)安全及應(yīng)用
- 異構(gòu)基因共表達(dá)網(wǎng)絡(luò)的分析方法
- Hands-On Chatbots and Conversational UI Development
- 物聯(lián)網(wǎng)信息安全
- 網(wǎng)絡(luò)互聯(lián)技術(shù)(實(shí)踐篇)
- PLC、現(xiàn)場(chǎng)總線及工業(yè)網(wǎng)絡(luò)實(shí)用技術(shù)速成
- Wireshark網(wǎng)絡(luò)分析就這么簡(jiǎn)單
- Working with Legacy Systems
- SAE原理與網(wǎng)絡(luò)規(guī)劃
- Getting Started with Memcached
- 網(wǎng)絡(luò)工程實(shí)施技術(shù)與方案大全
- 設(shè)備監(jiān)控技術(shù)詳解
- 網(wǎng)絡(luò)信息安全工程技術(shù)與應(yīng)用分析