官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 东兰县| 南京市| 韩城市| 南靖县| 永兴县| 望城县| 惠水县| 香港 | 昌邑市| 图片| 五华县| 左贡县| 土默特左旗| 磐安县| 衡山县| 洛宁县| 班戈县| 镇康县| 古浪县| 信阳市| 阳朔县| 乌什县| 星子县| 曲靖市| 讷河市| 米易县| 抚顺市| 扶余县| 肇庆市| 马山县| 新兴县| 满城县| 志丹县| 庐江县| 博湖县| 灵丘县| 开阳县| 荔浦县| 贵州省| 黄陵县| 岳阳县|