简体   繁体   中英

Why doesn't JSON.parse() work on this object?

const Http = new XMLHttpRequest(); 
const url='https://www.instagram.com/nasa/?__a=1'; 
Http.open("GET", url); 
Http.send();

Http.onreadystatechange = (e) => {
  console.log(Http.responseText); 
  var instaData = JSON.parse(Http.responseText);
  console.log(instaData); 
}

I'm trying to get a JSON object from an Instagram page so that I can extract some basic user data. The above code gets a string from Instagram that looks like a properly formatted JSON object, but when I try to use JSON.parse on it I get the error message "JSON.parse: unexpected end of data at line 1 column 1 of the JSON data".

I can't include the full output of Http.responseText because it's too long at 8,000+ characters, but it starts like this:

{"logging_page_id":"profilePage_528817151","show_suggested_profiles":true,"show_follow_dialog":false,"graphql":{"user":{"biography":"Explore the universe and discover our home planet. \ud83c\udf0d\ud83d\ude80\n\u2063\nUncover more info about our images:","blocked_by_viewer":false,"country_block":false,"external_url":"https://www.nasa.gov/instagram","external_url_linkshimmed":"https://l.instagram.com/?u=https%3A%2F%2Fwww.nasa.gov%2Finstagram&e=ATOO8om3o0ed_qw2Ih3Jp_aAPc11qkGuNDxhDV6EOYhKuEK5AGi9-L_yWuJiBASMANV4FrWW","edge_followed_by":{"count":53124504},"followed_by_viewer":false,"edge_follow":

You are trying to do a cross origin request without setting the Origin header. If a given api endpoint supports CORS, then when the Origin header is passed in the request it will reply with the "access-control-allow-origin" header.

I confirmed that the instagram url in your question does support CORS.

The following code using the fetch api works.

fetch('https://www.instagram.com/nasa/?__a=1', { mode: 'cors' })
  .then((resp) => resp.json())
  .then((ip) => {
    console.log(ip);
  });

You should read through the MDN CORS info https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS .

Here's also a fixed version of your original code:

const Http = new XMLHttpRequest();
const url = 'https://www.instagram.com/nasa/?__a=1';

Http.open("GET", url);
Http.setRequestHeader('Origin', 'http://local.geuis.com:2000');
Http.send();

Http.onreadystatechange = (e) => {
  if (Http.readyState === XMLHttpRequest.DONE && Http.status === 200) {
    console.log(Http.responseText);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM