【问题标题】:Why doesn't JSON.parse() work on this object?为什么 JSON.parse() 不能在这个对象上工作?
【发布时间】:2020-01-14 21:34:37
【问题描述】:
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数据”。

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

【问题讨论】:

  • 在这里帮助我们。 Http.responseText 究竟包含什么?
  • @Amy 根据错误消息,它看起来什么都不包含(数据意外结束)但是是的,@Lancey 请发布responseText 的实际值(你可能会看到它是空白的,这将为您提供问题的答案)
  • 水晶球坏了,
  • readyStatestatus 怎么样?中途阅读文档不是一个好主意
  • onreadystatechange 被多次调用,其中一些时间尚未检索到响应,因此您将对空(或 null/未定义)值进行操作

标签: javascript json instagram


【解决方案1】:

您正在尝试在未设置 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);
  }
}

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    相关资源
    最近更新 更多