尝试使用获取和通过模式:无心

JavaScript

达蒙斯丁

2020-03-11

我可以http://catfacts-api.appspot.com/api/facts?number=99通过邮递员到达终点,然后返回JSON

此外,我正在使用create-react-app,并希望避免设置任何服务器配置。

在我的客户端代码中,我试图用来fetch做同样的事情,但出现错误:

所请求的资源上不存在“ Access-Control-Allow-Origin”标头。因此,不允许访问源' http:// localhost:3000 '。如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。

所以我试图将一个对象传递到我的Fetch中,这将禁用CORS,如下所示:

fetch('http://catfacts-api.appspot.com/api/facts?number=99', { mode: 'no-cors'})
  .then(blob => blob.json())
  .then(data => {
    console.table(data);
    return data;
  })
  .catch(e => {
    console.log(e);
    return e;
  });

Interestingly enough the error I get is actually a syntax error with this function. I am not sure my actual fetch is broken, because when I remove the { mode: 'no-cors' } object, and supply it with a different URL it works just fine.

I have also tried to pass in the object { mode: 'opaque'} , but this returns the original error from above.

I belive all I need to do is disable CORS.. What am I missing?

第830篇《尝试使用获取和通过模式:无心》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
L番长 2020.03.11

一个非常简单的解决方案(配置需要2分钟)是使用来自以下位置的local-ssl-proxy软件包:npm

用法很简单:
1.安装软件包: npm install -g local-ssl-proxy
2.在运行local-server面罩时,使用local-ssl-proxy --source 9001 --target 9000

PS:更换--target 9000-- "number of your port"--source 9001--source "number of your port +1"

Harry小宇宙 2020.03.11

简单的解决方案:将以下内容添加到您要从中请求数据的php文件的顶部。

header("Access-Control-Allow-Origin: *");

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android