为什么JSON.parse()在此对象上不起作用?

问题描述 投票:-1回答:1
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":
javascript json instagram
1个回答
0
投票

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

我确认您问题中的instagram网址确实支持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);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.