为什么 JSON.parse() 对这个对象不起作用?

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); 
}

我正在尝试从 Instagram 页面获取 JSON 对象,以便提取一些基本用户数据。上面的代码从 Instagram 获取一个字符串,它看起来像一个格式正确的 JSON 对象,但是当我尝试在其上使用 JSON.parse 时,我收到错误消息 "JSON.parse: unexpected end of data at line 1 column 1 of the JSON data".

我无法包含 Http.responseText 的完整输出,因为它超过 8,000 个字符太长了,但它是这样开头的:

{"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":

您正在尝试在未设置来源的情况下执行跨来源请求 header。如果给定的 api 端点支持 CORS,则当在请求中传递 Origin header 时,它将使用 "access-control-allow-origin" header.

进行回复

我确认你问题中的 instagram url 确实支持 CORS。

以下使用提取 api 的代码有效。

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

您应该通读 MDN CORS 信息 https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

这也是您原始代码的固定版本:

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);
  }
}