📜  Node.js response.hasHeader() 方法

📅  最后修改于: 2022-05-13 01:56:46.131000             🧑  作者: Mango

Node.js response.hasHeader() 方法

response.hasHeader() (在 v7.7.0 中添加)属性是“ http ”模块的内置属性,如果名称标识的标头当前设置在传出标头中,则返回true 。标头名称匹配不区分大小写。 response.getHeaders()方法返回的对象在原型上并不继承自 JavaScript 对象。

为了得到响应和正确的结果,我们需要导入' http '模块。

const http = require('http');

句法:

response.hasHeader(name);

参数:此属性接受一个如上所述和如下所述的参数:

  • name:它是要检查是否存在的标头值的名称。

返回值< Boolean > 如果当前设置了标头的名称,则返回True ,否则返回False

下面的示例说明了在 Node.js 中response.hasHeader()属性的使用。

示例 1:文件名:index.js

Javascript
// Node.js program to demonstrate the
// response.hasHeaders() 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('', 'Beta'); // Throws Error
    // response.setHeader(); // Throws Error
    response.setHeader('Alfa1', '');
    response.setHeader('Alfa2', 5);
    response.setHeader('Cookie-Setup',
            ['Alfa=Beta', 'Beta=Romeo']);
 
    // Checking the headers
    const hasHeardere = response.hasHeader('Cookie-Setup');
    const hasHearder0 = response.hasHeader('Alfa');
    const hasHearder1 = response.hasHeader('Alfa1');
    const hasHearder2 = response.hasHeader('Alfa2');
    const hasHearder3 = response.hasHeader('Content-Type');
 
    // Printing output
    console.log("When Header is set an Array:", hasHeardere);
    console.log("When Header is set Beta:", hasHearder0);
    console.log("When Header is set '':", hasHearder1);
    console.log("When Header is set number 5:", hasHearder2);
    console.log("When Header is not set:", hasHearder3);
 
    // Getting the set Headers
    const headers = response.getHeaders();
 
    // Printing those headers
    console.log(headers);
 
    var Output = "Hello Geeksforgeeks..., " +
        "When Header is set 'Beta': " + hasHeardere +
        ", When Header is set '':" + hasHearder1 +
        ", When Header is set number 5:" + hasHearder2 +
        ", When Header is not set:" + hasHearder3;
 
    // Prints Hello Geeksforgeeks...
    // on browser in response
    response.write(Output);
    response.end();
});
 
// Listening to http Server
httpServer.listen(PORT, () => {
    console.log("Server is running at port 3000...");
});


使用以下命令运行index.js文件:

node index.js

输出:

// 现在在浏览器中运行 http://localhost:3000/。

参考: https://nodejs.org/api/http.html#http_response_hasheader_name