首页 > 解决方案 > SyntaxError: Unexpected token < in JSON at position 0 如何解决

问题描述

我正在制作一个新闻网站并收到此错误。

SyntaxError: 位置 0 处的 JSON 中的意外标记 <

如何解决?

function getnews(){
    fetch('https://cors-anywhere.herokuapp.com/http://newsapi.org/v2/top-headlines?q=india&apiKey=f4176dc9b5194205b4ea64370c715b9b',{headers: new Headers({"X-Requested-With":"hgsofuvuwaoao"})})
    .then(a => a.json()).then((response) =>{
console.log(response);
    })
}
getnews();

标签: javascriptpythonnode.jserror-handling

解决方案


您确定从正确的 URL 请求?

https://cors-anywhere.herokuapp.com/http://newsapi.org/v2/top-headlines?q=india&apiKey=f4176dc9b5194205b4ea64370c715b9b

对我来说看起来像两个 URL。如果你输入它“原始”,你会得到一个 html 网站,上面写着:Missing required request header. Must specify one of: origin,x-requested-with.

Json 数据位于

https://newsapi.org/v2/top-headlines?q=india&apiKey=f4176dc9b5194205b4ea64370c715b9b

由于它正在尝试解析 html,因此它会读取<html 标签并在那里引发错误。尝试更改 URL 并查看是否可以修复它。

您提供的 URL 的原始数据是

<html><head><link rel="stylesheet" href="resource://content-accessible/plaintext.css"></head><body><pre>Missing required request header. Must specify one of: origin,x-requested-with</pre></body></html>

可以理解,这不是有效的 json 格式。


推荐阅读