最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to make a JSON object out of getAllResponseHeaders method - Stack Overflow

programmeradmin1浏览0评论

I am currently writing a google chrome extension, and I need to find out information about websites' response headers. In order to do this, I used the getAllResponseHeaders method, but I need to put it in a JSON object. Unfortunately, I keep getting the error message SyntaxError: Unexpected token D in JSON at position 0 at main.

Here is the code I am using to do this so far:

xmlhttp.open("GET", url, false);
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        allResponseHeaders = xmlhttp.getAllResponseHeaders();
    }
};
xmlhttp.send();

var responseHeaders = JSON.parse(allResponseHeaders);
obj.headers = responseHeaders;

When I put an alert immediately after the allResponseHeaders = xmlhttp.getAllResponseHeaders(); call, the alert shows that the call was a success; the response headers have all been retrieved. The first response header is the Date, which I think has to do with the Unexpected token D part of my error message, but I don't know why it won't parse properly. How do I fix this? Thanks in advance.

EDIT: I would like my JSON object to look something like this:

{
  "headers": {
    "Date": "June 20, 2016",
    "Content-Type": "charset=UTF/8",
    ...
  }
}

I am currently writing a google chrome extension, and I need to find out information about websites' response headers. In order to do this, I used the getAllResponseHeaders method, but I need to put it in a JSON object. Unfortunately, I keep getting the error message SyntaxError: Unexpected token D in JSON at position 0 at main.

Here is the code I am using to do this so far:

xmlhttp.open("GET", url, false);
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        allResponseHeaders = xmlhttp.getAllResponseHeaders();
    }
};
xmlhttp.send();

var responseHeaders = JSON.parse(allResponseHeaders);
obj.headers = responseHeaders;

When I put an alert immediately after the allResponseHeaders = xmlhttp.getAllResponseHeaders(); call, the alert shows that the call was a success; the response headers have all been retrieved. The first response header is the Date, which I think has to do with the Unexpected token D part of my error message, but I don't know why it won't parse properly. How do I fix this? Thanks in advance.

EDIT: I would like my JSON object to look something like this:

{
  "headers": {
    "Date": "June 20, 2016",
    "Content-Type": "charset=UTF/8",
    ...
  }
}
Share Improve this question edited Jun 20, 2016 at 14:07 Cameron Payton asked Jun 20, 2016 at 13:51 Cameron PaytonCameron Payton 4321 gold badge8 silver badges20 bronze badges 4
  • 1 JSON.parse() isn't going to work on a string that doesn't contain JSON...that's like asking why parseFloat() doesn't work on the string "hello". – nnnnnn Commented Jun 20, 2016 at 13:54
  • Is there anyway to convert it to a JSON string? – Cameron Payton Commented Jun 20, 2016 at 13:56
  • What is your desired output format, specifically? Please edit your question to show an example. Also, you might want to add console.log(allResponseHeaders) immediately after assigning the value to that variable, so that you can see what format it is in (I think it should be one header per line separated by carriage returns). – nnnnnn Commented Jun 20, 2016 at 14:01
  • I edited to show you what the ideal json format should be, and yes it is giving me each field separated by a line – Cameron Payton Commented Jun 20, 2016 at 14:08
Add a ment  | 

4 Answers 4

Reset to default 7

See https://msdn.microsoft./en-us/library/ms536428(v=vs.85).aspx. The return headers are a crlf delimited string where each line contains key values separated by a colon. You will probably have to adjust the code below to account for whitespace.

var arr = allResponseHeaders.split('\r\n');
var headers = arr.reduce(function (acc, current, i){
      var parts = current.split(': ');
      acc[parts[0]] = parts[1];
      return acc;
}, {});

I use the following function to extract all response headers as JS object using getAllResponseHeaders():

function getResponseHeaderMap(xhr) {
  const headers = {};
  xhr.getAllResponseHeaders()
      .trim()
      .split(/[\r\n]+/)
      .map(value => value.split(/: /))
      .forEach(keyValue => {
        headers[keyValue[0].trim()] = keyValue[1].trim();
      });
  return headers;
}

You should put JSON.parse logic inside the callback onreadystatechange, since Ajax is an asynchronous call and allResponseHeaders may not be initialized when you use it right after sending the http request.

Simplified version of the accepted answer and fixed issue reported by @Emrah Tuncel :

The first item of the return value is incorrect. { "": undefined }

// ES6:
const headers = request.getAllResponseHeaders().trim().split('\r\n').reduce((acc, current) => {
      const [x,v] = current.split(': ');
      return Object.assign(acc, { [x] : v });
}, {});
发布评论

评论列表(0)

  1. 暂无评论