Javascript Fetch in React在url之前添加localhost
我正在使用fetch通过GET请求读取一些数据 大概是这样的:Javascript Fetch in React在url之前添加localhost,javascript,reactjs,localhost,fetch,package.json,Javascript,Reactjs,Localhost,Fetch,Package.json,我正在使用fetch通过GET请求读取一些数据 大概是这样的: fetch( 'myurl.com/data', requestOptions ) .then((response) => response.text()) .then((result) => console.log(result)) .catch((error) => console.log('error', error)); fetch( 'http:
fetch(
'myurl.com/data',
requestOptions
)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log('error', error));
fetch(
'http://myurl.com/data',
....
我已经在postman上测试过了,它运行良好,返回数据
问题是,当我在浏览器中调用它时,它返回的是HTML而不是JSON
在Dev Tools->Network->Initiator中,url看起来不同,它在其开头添加了“localhost…”
像这样:http://localhost:3000/store/orders/myurl.com/data
。正因为如此,url被破坏了,它不会返回JSON
没有http://localhost:3000/store/orders
在项目中,它位于package.json此行:“主页”:“/store/orders/”
有没有解决此问题的方法?请尝试不要忽略协议部分
http://
,这样您的获取调用将如下所示:
fetch(
'myurl.com/data',
requestOptions
)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log('error', error));
fetch(
'http://myurl.com/data',
....
myurl.com
的确切值是多少?使用http://myurl.com/data
nomyurl.com/data
addhttp://
或https://
在URL前面我添加了该部分,它现在抛出此错误:“从源”获取的访问已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许来源”标头。如果不透明响应满足您的需要,请将请求的模式设置为“no cors”,以获取禁用cors的资源。是的,这是预期的行为(您需要研究另一个问题)。给你方向:选项如何解决:1。部署您的项目,设置TLS并使用https协议2。(测试)将myurl.com
添加到chrome浏览器设置3中的受信任源。(测试)从服务器端(myurl.com)临时破解CORS策略这是另一个大问题,请单独研究。。。基本上,这是谷歌chrome为了安全而做的事情。我在requestOptions中添加了:模式:“no cors”
,这样错误就不会再出现了。现在只是一条简短的错误消息,上面写着:net::ERR_检查飞行前选项请求是否成功(它显示在chrome开发者工具网络选项卡中)。