Handling Response Headers
# Handling Response Headers
# Requirements Analysis
The value we get from the XMLHttpRequest object's getAllResponseHeaders method is a string like the following:
date: Fri, 05 Apr 2019 12:40:49 GMT
etag: W/"d-Ssxx4FRxEutDLwo2+xkkxKc4y0k"
connection: keep-alive
x-powered-by: Express
content-length: 13
content-type: application/json; charset=utf-8
1
2
3
4
5
6
2
3
4
5
6
Each line ends with a carriage return and newline (\r\n), which serve as delimiters between header properties. For the string above, we want to parse it into an object structure:
{
date: 'Fri, 05 Apr 2019 12:40:49 GMT'
etag: 'W/"d-Ssxx4FRxEutDLwo2+xkkxKc4y0k"',
connection: 'keep-alive',
'x-powered-by': 'Express',
'content-length': '13'
'content-type': 'application/json; charset=utf-8'
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# Implementing and Applying the parseHeaders Function
Based on the requirements analysis, we need to implement a parseHeaders utility function.
helpers/headers.ts:
export function parseHeaders(headers: string): any {
let parsed = Object.create(null)
if (!headers) {
return parsed
}
headers.split('\r\n').forEach(line => {
let [key, val] = line.split(':')
key = key.trim().toLowerCase()
if (!key) {
return
}
if (val) {
val = val.trim()
}
parsed[key] = val
})
return parsed
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Then we use this utility function:
xhr.ts:
const responseHeaders = parseHeaders(request.getAllResponseHeaders())
1
Now if we revisit the earlier demo, we can see that the response headers field has been parsed from a string into an object structure. Next, let's solve the second outstanding issue: handling the response data field.
Edit (opens new window)
Last Updated: 2026/03/21, 12:14:36