我正在尝试使用JavaScript进行抓取请求。目标是将所有JSON从此处导入到我的React应用程序中。我认为我使用的是最简单的方法之一,但我仍在设法弄乱。
我的预期结果是console.log()
带有json数据的输出。相反,我得到的结果是一个错误,指出
未捕获(承诺)SyntaxError:JSON中位置0处的意外令牌<
在探索问题时,我将一些代码更改.then(results => results.json())
为.then(results => results.text())
。那向我显示了我的提取请求得到的内容。我发现它根本没有到达所提供的URL,而是返回了我应用程序的主页(我认为index.html位于“ /”)。奇怪的。
这是我的代码的简化版本:
import React from "react";
const hardcoded_url =
"https://www.reddit.com/r/learnprogramming/new/.json?count=25&after=";
getJSON = () => {
fetch(this.hardcoded_url)
.then(results => results.json())
.then(data => console.log(data));
};
render() {
return (
// <react stuff>
)
}
我console.log(data)
打印出来的实际上index.html
是我的React应用程序的内容:
<!DOCTYPE html>
<html lang="en">
<!--- blah blah --->
</html>
我什至可以在“开发人员工具”网络标签中看到请求已关闭。对我来说,它看起来不正确。它注册为undefined
下Network -> Headers -> General
:
请求网址:http:// localhost:3000 / undefined
请求方法:GET
状态码:304未修改
我已尝试Google搜索错误消息和javascript fetch url returns index.html
。后者使我这个网页它看起来前途无量,但加入了“代理”行到我的package.json没有帮助(具体地讲,我说:"proxy": "http://localhost:3000"
)。我也不认为这是凭证问题,因为我可以仅通过浏览器访问URL。
我不明白为什么这对我不起作用。我正在从别人的github项目复制代码形式给我自己的Reddit小克隆。他们的作品...
hardcoded_url
是一个const而不是class变量。问题是通过this.hardcoded_url访问它。
fetch(hardcoded_url)
是这里的正确方法。
this.hardcoded_url is undefined
因此,fetchundefined
的URL被认为是相对于本地主机的URL,因此API是http:// localhost:3000 / undefined而不是实际的URL
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句