Javascript get current headers

XMLHttpRequest: getAllResponseHeaders() method

The XMLHttpRequest method getAllResponseHeaders() returns all the response headers, separated by CRLF, as a string, or returns null if no response has been received.

If a network error happened, an empty string is returned.

Note: For multipart requests, this returns the headers from the current part of the request, not from the original channel.

Syntax

Parameters

Return value

A string representing all of the response’s headers (except those whose field name is Set-Cookie ) separated by CRLF, or null if no response has been received. If a network error happened, an empty string is returned.

An example of what a raw header string looks like:

date: Fri, 08 Dec 2017 21:04:30 GMT\r\n content-encoding: gzip\r\n x-content-type-options: nosniff\r\n server: meinheld/0.6.1\r\n x-frame-options: DENY\r\n content-type: text/html; charset=utf-8\r\n connection: keep-alive\r\n strict-transport-security: max-age=63072000\r\n vary: Cookie, Accept-Encoding\r\n content-length: 6502\r\n x-xss-protection: 1; mode=block\r\n 

Each line is terminated by both carriage return and line feed characters ( \r\n ). These are essentially delimiters separating each of the headers.

Note: In modern browsers, the header names are returned in all lower case, as per the latest spec.

Examples

This example examines the headers in the request’s readystatechange event. The code shows how to obtain the raw header string, as well as how to convert it into an array of individual headers and then how to take that array and create a mapping of header names to their values.

const request = new XMLHttpRequest(); request.open("GET", "foo.txt", true); request.send(); request.onreadystatechange = () =>  if (request.readyState === this.HEADERS_RECEIVED)  // Get the raw header string const headers = request.getAllResponseHeaders(); // Convert the header string into an array // of individual headers const arr = headers.trim().split(/[\r\n]+/); // Create a map of header names to values const headerMap = >; arr.forEach((line) =>  const parts = line.split(": "); const header = parts.shift(); const value = parts.join(": "); headerMap[header] = value; >); > >; 

Once this is done, you can, for example:

const contentType = headerMap["content-type"]; 

This obtains the value of the Content-Type header into the variable contentType .

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on May 10, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Headers

The Headers interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing headers from the list of the request’s headers.

A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. You can add to this using methods like append() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence.

For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names.

A Headers object also has an associated guard, which takes a value of immutable , request , request-no-cors , response , or none . This affects whether the set() , delete() , and append() methods will mutate the header. For more information see Guard.

You can retrieve a Headers object via the Request.headers and Response.headers properties, and create a new Headers object using the Headers() constructor.

An object implementing Headers can directly be used in a for. of structure, instead of entries() : for (const p of myHeaders) is equivalent to for (const p of myHeaders.entries()) .

Note: you can find out more about the available headers by reading our HTTP headers reference.

Constructor

Creates a new Headers object.

Instance methods

Appends a new value onto an existing header inside a Headers object, or adds the header if it does not already exist.

Deletes a header from a Headers object.

Returns an iterator allowing to go through all key/value pairs contained in this object.

Executes a provided function once for each key/value pair in this Headers object.

Returns a String sequence of all the values of a header within a Headers object with a given name.

Returns an array containing the values of all Set-Cookie headers associated with a response.

Returns a boolean stating whether a Headers object contains a certain header.

Returns an iterator allowing you to go through all keys of the key/value pairs contained in this object.

Sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.

Returns an iterator allowing you to go through all values of the key/value pairs contained in this object.

Note: To be clear, the difference between Headers.set() and Headers.append() is that if the specified header does already exist and does accept multiple values, Headers.set() will overwrite the existing value with the new one, whereas Headers.append() will append the new value onto the end of the set of values. See their dedicated pages for example code.

Note: All of the Headers methods will throw a TypeError if you try to pass in a reference to a name that isn’t a valid HTTP Header name. The mutation operations will throw a TypeError if the header has an immutable Guard. In any other failure case they fail silently.

Note: When Header values are iterated over, they are automatically sorted in lexicographical order, and values from duplicate header names are combined.

Examples

In the following snippet, we create a new header using the Headers() constructor, add a new header to it using append() , then return that header value using get() :

const myHeaders = new Headers(); myHeaders.append("Content-Type", "text/xml"); myHeaders.get("Content-Type"); // should return 'text/xml' 

The same can be achieved by passing an array of arrays or an object literal to the constructor:

let myHeaders = new Headers( "Content-Type": "text/xml", >); // or, using an array of arrays: myHeaders = new Headers([["Content-Type", "text/xml"]]); myHeaders.get("Content-Type"); // should return 'text/xml' 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 26, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Headers: get() method

The get() method of the Headers interface returns a byte string of all the values of a header within a Headers object with a given name. If the requested header doesn’t exist in the Headers object, it returns null .

For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names.

Syntax

Parameters

The name of the HTTP header whose values you want to retrieve from the Headers object. If the given name is not the name of an HTTP header, this method throws a TypeError . The name is case-insensitive.

Return value

A String sequence representing the values of the retrieved header or null if this header is not set.

Examples

Creating an empty Headers object is simple:

const myHeaders = new Headers(); // Currently empty myHeaders.get("Not-Set"); // Returns null 

You could add a header to this using Headers.append , then retrieve it using get() :

.append("Content-Type", "image/jpeg"); myHeaders.get("Content-Type"); // Returns "image/jpeg" 

If the header has multiple values associated with it, the byte string will contain all the values, in the order they were added to the Headers object:

.append("Accept-Encoding", "deflate"); myHeaders.append("Accept-Encoding", "gzip"); myHeaders.get("Accept-Encoding"); // Returns "deflate, gzip" myHeaders .get("Accept-Encoding") .split(",") .map((v) => v.trimStart()); // Returns [ "deflate", "gzip" ] 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Getting Response Headers with the Javascript Fetch API

I’ve Googled-skimmed-copied plenty of answers in my day, so I’m going to start this post with the tl;dr — if you’re here for the fix, just read the first part. If you’re curious as to more of what’s going on (use cases, methods, etc), read further!

Getting the headers via method entries()

The headers are hidden in an entries() method that doesn’t return an object, but an iterator, that then gives access to the headers in a key / value format through a for. of loop. (More on this at MDN)

For example, if you fetch my site and log out the loop, this is what you’ll get:

// code fetch('https://stevemiller.dev') .then((response) =>  for (var pair of response.headers.entries())  console.log(pair[0]+ ': '+ pair[1]); > >); // logs cache-control: max-age=600 content-type: text/html; charset=utf-8 expires: Sun, 07 Jul 2019 03:54:43 GMT last-modified: Sun, 07 Jul 2019 03:43:47 GMT 

More info: Response Header Uses

A number of RESTful APIs use response headers to indicate important information after a call. For example, some third-party APIs will include current rate limit information in custom headers.

In my case, I was using the handy json-server package for some test data.

When running a query on the json-server dataset, it returns a header with the total number of results for that query to help with paginating ( x-total-count ).

Javascript Fetch API

Using a React front-end, I was calling the json-server API using the built-in fetch functionality with Javascript:

fetch(`/events?q=$query>&_page=$page>`) .then((response) =>  return response.json(); >) // then setting state, etc 

(I love fetch because it’s built into Javascript, so no need for an extra package)

But, to help with pagination, I needed to know exactly how many “pages” worth of content this query would provide. Accessing the headers like this logged an empty object:

console.log(reponse.headers); // ouptu: Headers <> 

This is because the headers are not an object, they’re an iterator

Accessing the headers using for. of and entries()

You can’t directly access the headers on the response to a fetch call – you have to iterate through after using the entries() method on the headers. Code sample (using react and looking for a query count) below:

From here, you could construct your own object via the loop, or filter for specific values (like I did at the top of the post).

Looking for a Javascript developer? Check out my portfolio if you’re intrigued or start the conversation by reaching out to steve [at] stevemiller.dev

Источник

Читайте также:  Java сумма всех значений массива
Оцените статью