繁体   English   中英

为什么 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:JSON 的第 1 行第 1 列的数据意外结束”数据”。

我无法包含 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":

您正在尝试在不设置 Origin 标头的情况下执行跨源请求。 如果给定的 api 端点支持 CORS,则在请求中传递 Origin 标头时,它将使用“access-control-allow-origin”标头进行回复。

我确认您问题中的 instagram 网址确实支持 CORS。

以下使用 fetch 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);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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