Node.js response.getHeaderNames() 方法
response.getHeaderNames() (在 v7.7.0 中添加)方法是“ http ”模块的内置应用程序编程接口,它返回一个包含当前传出标头的唯一名称的数组。所有标题名称都是小写的。
当使用response.setHeader()设置了 headers 时,它们将与传递给 response.writeHead() 的任何 headers 合并,并且传递给response.writeHead ()的 headers 具有优先级。
为了得到响应和正确的结果,我们需要导入' http '模块。
句法:
const http = require('http');
句法:
response.getHeaderNames()
参数:此属性不接受任何参数。
返回值:它以字符串格式返回所有标题的名称,如下面的示例所述。
下面的示例说明了在 Node.js 中使用response.getHeaderNames()方法。
示例 1:文件名:index.js
// Node.js program to demonstrate the
// response.getHeaderNames() Method
// Importing http module
var http = require('http');
// Setting up PORT
const PORT = process.env.PORT || 3000;
// Creating http Server
var httpServer = http.createServer(
function(req, response) {
// Setting up Headers
response.setHeader('Alfa', 'Beta');
response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie',
['foo=bar', 'bar=baz']);
const headerNames = response.getHeaderNames();
console.log(headerNames);
response.end("200, ok");
});
// Listening to http Server
httpServer.listen(PORT, () => {
console.log(
"Server is running at port 3000...");
});
输出:
Output: In Console
>> Server is running at port 3000…
>> [ ‘alfa’, ‘foo’, ‘set-cookie’ ]
现在在浏览器中运行http://localhost:3000/ 。
输出:在浏览器中
200, ok
示例 2:文件名:index.js
// Node.js program to demonstrate the
// response.getHeaderNames() Method
// Importing http module
var http = require('http');
// Setting up PORT
const PORT = process.env.PORT || 3000;
// Creating http Server
var httpServer = http.createServer(
function(req, response) {
// Setting up Headers
response.setHeader('Alfa', 'Beta');
response.setHeader('Alfa1', '');
response.setHeader('Alfa2', 5);
response.setHeader('Cookie-Setup',
['Alfa=Beta', 'Beta=Romeo']);
// Getting the set Headers
const headers = response.getHeaders();
const headerNames = response.getHeaderNames();
// Printing those headers
console.log(headers);
// Printing headerNames
console.log(headerNames);
var Output = "Hello Geeksforgeeks...,"
+ " Available headerNames are:"
+ JSON.stringify(headerNames);
// Prints Output on the browser in response
response.write(Output);
response.end('ok');
});
// Listening to http Server
httpServer.listen(PORT, () => {
console.log("Server is running at port 3000...");
});
使用以下命令运行index.js文件:
node index.js
输出:
Output: In Console
Server is running at port 3000…
>> [Object: null prototype] {
alfa: ‘Beta’,
alfa1: ”,
alfa2: 5,
‘cookie-setup’: [ ‘Alfa=Beta’, ‘Beta=Romeo’ ]}
>> [ ‘alfa’, ‘alfa1’, ‘alfa2’, ‘cookie-setup’ ]
现在在浏览器中运行http://localhost:3000/ 。
输出:在浏览器中
Hello Geeksforgeeks…, Available headers and trailers are:{“alfa1″:””, “cookie-setup”:[“Alfa=Beta”, “Beta=Romeo”],
“content-type”:”text/plain”, “trailer”:”Content-MD5″}ok
参考: https://nodejs.org/api/http.html#http_response_getheadernames