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

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.

主站蜘蛛池模板: 凌云县| 商都县| 体育| 林口县| 绍兴市| 霞浦县| 福鼎市| 黄骅市| 仲巴县| 武功县| 渝北区| 禹州市| 苍南县| 会理县| 文成县| 郁南县| 高碑店市| 若尔盖县| 朔州市| 紫云| 双流县| 临漳县| 苏尼特左旗| 侯马市| 东兴市| 卢湾区| 宁晋县| 张家界市| 铁力市| 江都市| 临湘市| 凤冈县| 宝兴县| 咸阳市| 元江| 井冈山市| 武汉市| 莆田市| 安仁县| 铜川市| 德钦县|