- XMLHttpRequest: getAllResponseHeaders() method
- Syntax
- Parameters
- Return value
- Examples
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Request: headers property
- Value
- Examples
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- Как отправить или получить HTTP заголовки на JavaScript
- Как отправить HTTP заголовки запроса
- Как получить HTTP заголовки ответа
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.
Request: headers property
The headers read-only property of the Request interface contains the Headers object associated with the request.
Value
Examples
In the following snippet, we create a new request using the Request() constructor (for an image file in the same directory as the script), then save the request headers in a variable:
const myRequest = new Request("flowers.jpg"); const myHeaders = myRequest.headers; // Headers <>
To add a header to the Headers object we use Headers.append ; we then create a new Request along with a 2nd init parameter, passing headers in as an init option:
const myHeaders = new Headers(); myHeaders.append("Content-Type", "image/jpeg"); const myInit = method: "GET", headers: myHeaders, mode: "cors", cache: "default", >; const myRequest = new Request("flowers.jpg", myInit); const myContentType = myRequest.headers.get("Content-Type"); // returns 'image/jpeg'
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.
Как отправить или получить HTTP заголовки на JavaScript
05.12.18 ИТ / JavaScript 14105
Обычно для работы с заголовками используется серверный язык, однако можно попробовать использовать и JavaScript (JS).
Как отправить HTTP заголовки запроса
Отправить заголовки на JavaScript можно при помощи Ajax-запросов. На чистом языке без применения библиотек это может выглядеть так:
var request = new XMLHttpRequest(); request.open('GET', document.location, false); request.setRequestHeader('Accept', 'text/plain'); request.setRequestHeader('Content-Type', 'text/plain'); request.setRequestHeader('Content-Language', 'en-US'); request.send(null); request.getAllResponseHeaders().toLowerCase();
Как получить HTTP заголовки ответа
Получить заголовки на JavaScript задача посложней, так как это язык работает на стороне клиента. Но можно отправить запрос на сервер средствами Ajax и получить примерно похожие заголовки при помощи функции getAllResponseHeaders. Примерный код:
var request = new XMLHttpRequest(); request.open('GET', document.location, false); request.send(null); request.getAllResponseHeaders().toLowerCase();
Таким образом, отправить или получить заголовки можно и при помощи языка JavaScript, а не только при помощи серверных языков, наподобие PHP.