简体   繁体   English

如何解决 Fetch API js 中的 CORS 错误

[英]How to resolve CORS error in Fetch API js

I want to fetch json from my subdomain (File Hosting Server) , but it gets the following error:我想从我的子域(文件托管服务器)中获取 json,但它收到以下错误:

Reason: CORS request did not succeed)原因:CORS请求没有成功)

(Reason: CORS header 'Access-Control-Allow-Origin' missing (原因:缺少 CORS 标头“Access-Control-Allow-Origin”

my similar code:我的类似代码:

async function getData(url = '', data = {}) {
    const response = await fetch(url, {
    method: 'get',
    mode: 'no-cors',
    headers: {
       'Access-Control-Allow-Origin' : '*'
    },
  });
  return response.json();
}

I add我加

headers: {
}                               'Access-Control-Allow-Origin' : '*'

but don't work.但不工作。

I add我加

mode: no-cors

to code, fetch file but return response status 0 , mode: 'opaque'.编码,获取文件但返回响应状态 0 ,模式:'不透明'。

please help me.请帮我。

CORS 是通过服务器端配置的,所以你需要在你的文件托管服务器上配置

I believe you know what you are trying to achieve here.我相信你知道你在这里想要实现什么。 Fetch with CORS use case is very tricky.使用 CORS 用例获取非常棘手。 CORS is driven by server settings. CORS 由服务器设置驱动。 All the headers ACCESS-CONTROL-* are set at the server end.所有标头 ACCESS-CONTROL-* 都设置在服务器端。

Access-Control-Allow-Origin is for CORS, and the client honor this header when dealing with the cross-origin request. Access-Control-Allow-Origin 是针对 CORS 的,客户端在处理跨域请求时会遵循这个标头。 The server sends this header in the response.服务器在响应中发送此标头。 From the server end, you have to pass this header.从服务器端,您必须传递此标头。 In your response, you have to pass this header.在您的回复中,您必须传递此标头。

Access-Control-Allow-Origin: *

Or if you are dealing with credentials (Wild card not supported here):-或者,如果您正在处理凭据(此处不支持通配符):-

Access-Control-Allow-Origin: https://foo.example 

Reference:-参考:-

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

如果您的主机 api 文件您要调用的是 php,请将其添加到第 2 行的 php 文件中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM