在javascript中使用提取请求API有CORS政策错误 [英] Requesting API with fetch in javascript has CORS policy error

查看:474
本文介绍了在javascript中使用提取请求API有CORS政策错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的JavaScript代码中调用某些具有访存功能的API.我正在使用我的机器上的ReactJs进行开发,并且在同一网络中进行另一项开发,在另一台机器上使用.net开发API.使用邮递员,我可以调用API,但不能获取.我尝试在其他服务器上调用另一个API,结果成功.

我正在使用访存,也尝试使用axios.我在堆栈中的另一个问题中发现该API溢出: https://gturnquist-quoters.cfapps. io/api/random . 答案是说要尝试获取它们,而我会尝试但再次引发相同的错误.

我的代码来获取gturnquist API:

const myHeader = new Headers();
myHeader.append('Content-Type', 'application/json');
fetch('http://gturnquist-quoters.cfapps.io/api/random', {
  method: 'GET', headers: myHeader,
})
 .then((res) => {
   console.log(res);
   return {};
 })
 .then(res => console.log(res));

和我的代码来获取我需要的API:

const myHeader = new Headers();

const token = 'mytoken';
myHeader.append('id-tenant', token);
myHeader.append('Content-Type', 'application/json');

const id = 'myid';
const url = 'myurl';

fetch(`http://10.1.1.35/${url}/${id}`, {
  method: 'GET',
  headers: myHeader,
}).then(res => res.json()).then(res => console.log(res));

当我尝试调用API时遇到此错误

OPTIONS http://10.1.1.35/url/id 503(服务不可用)

可从原始位置获取" http://10.1.1.35/url/id "处的访问权限" http://localhost:3000 "已被CORS策略阻止:对预检请求的响应未通过访问控制检查:所请求的资源上没有"Access-Control-Allow-Origin"标头.如果不透明的响应可以满足您的需求,请将请求的模式设置为"no-cors",以在禁用CORS的情况下获取资源.

未捕获(承诺)TypeError:无法获取

这是服务器端错误还是javascript错误?

在我的服务器中,API的配置类似于 Rajkumar Peter

的答案

编辑:我的网络错误

我看到的尝试解决我的错误的问题:
使用instagram API获取CORS错误
在获取api中启用CORS
通过获取API GET请求管理CORS
>信息提取具有CORS政策阻止的错误提取
对预检请求的响应未通过访问控制检查

解决方案

从网络浏览器执行API调用时,通常会执行预检检查".从本质上讲,这是浏览器向您的API发送请求(在您自己的API调用之前),检查允许执行的操作以及是否值得发送实际请求的地方.

为此,它使用OPTIONS方法(而不是GET,POST等).

如果尚未将您的API终结点配置为接受OPTIONS请求,则来自浏览器的预检请求将失败-并且将中止发送您的请求.

要解决您的问题,您需要将API配置为接受OPTIONS方法.您还应该检查允许哪些来源(连接到API的客户端的IP地址).

I'm trying to call some APIs with fetch in my javascript code. I'm developing with ReactJs in my machine and have another development in the same network developing the API with .net in another machine. With postman, I can call the API, but with fetch no. I try to call another API in other server and the result was successful.

I'm using fetch and tried to use axios too. I have found in other question in stack overflow this API: https://gturnquist-quoters.cfapps.io/api/random. The answer says to try to fetch they and I try but throw same error again.

My code to fetch the gturnquist API:

const myHeader = new Headers();
myHeader.append('Content-Type', 'application/json');
fetch('http://gturnquist-quoters.cfapps.io/api/random', {
  method: 'GET', headers: myHeader,
})
 .then((res) => {
   console.log(res);
   return {};
 })
 .then(res => console.log(res));

and my code to fetch the API that i need:

const myHeader = new Headers();

const token = 'mytoken';
myHeader.append('id-tenant', token);
myHeader.append('Content-Type', 'application/json');

const id = 'myid';
const url = 'myurl';

fetch(`http://10.1.1.35/${url}/${id}`, {
  method: 'GET',
  headers: myHeader,
}).then(res => res.json()).then(res => console.log(res));

I have this errors when I try to call an API

OPTIONS http://10.1.1.35/url/id 503 (Service Unavailable)

Access to fetch at 'http://10.1.1.35/url/id' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Uncaught (in promise) TypeError: Failed to fetch

It's a server side error or javascript error?

In my server, the API is configured like the answer of Rajkumar Peter

EDIT: My network error

Questions i have see to try handle my error:
Fetch CORS error with instagram api
Enable CORS in fetch api
managing CORS with fetch API GET request
React fetch has error fetch was blocked by CORS policy
Response to preflight request doesn't pass access control check

解决方案

When performing an API call from a web browser, it will often do something called a "preflight check". This is essentially where the browser sends a request to your API (ahead of your own API call), to check what it is allowed to do and whether it's even worth sending the actual request.

To do this, it uses the OPTIONS method (instead of GET, POST .etc).

If your API endpoint hasn't been configured to accept OPTIONS requests, then the preflight request from the browser will fail - and it will abort sending your request.

To fix your issue, you need to configure your API to accept OPTIONS methods. You should also check which origins (IP addresses of clients connecting to the API) are allowed.

这篇关于在javascript中使用提取请求API有CORS政策错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆