response.writeHead(statusCode[, statusMessage][, headers])
發送一個響應頭給請求。 狀態碼是一個三位數的 HTTP 狀態碼,如 404
。 最后一個參數 headers
是響應頭。 第二個參數 statusMessage
是可選的狀態描述。
例子:
const body = 'hello world'; response.writeHead(200, { 'Content-Length': Buffer.byteLength(body), 'Content-Type': 'text/plain' });
該方法在消息中只能被調用一次,且必須在 response.end()
被調用之前調用。
如果在調用該方法之前調用 response.write()
或 response.end()
,則隱式的響應頭會被處理並調用該函數。
response.setHeader()
設置的響應頭會與 response.writeHead()
設置的響應頭合並,且 response.writeHead()
的優先。
// 返回 content-type = text/plain const server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok'); });
注意,Content-Length
是以字節(而不是字符)為單位的。 上面的例子行得通是因為字符串 'hello world'
只包含單字節字符。 如果響應主體包含高級編碼的字符,則應使用 Buffer.byteLength()
來確定在給定編碼中的字節數。 Node.js 不會檢查 Content-Length
與已發送的響應主體的長度是否相同。
如果響應頭字段的名稱或值包含無效字符,則拋出 TypeError
錯誤。