我试图获取一个旧网站的URL,发生了一个错误:

Fetch API cannot load http://xyz.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://abc' is therefore not allowed access.
If an opaque response serves your needs, set the request's mode to 'no-cors'
to fetch the resource with CORS disabled.

我理解的消息,并试图做一个请求,返回一个不透明的响应:

fetch("http://xyz", {'mode': 'no-cors'})

好的,它现在工作了……但是我看不懂。= \

那么,这种不透明的回应的目的是什么呢?


JavaScript不能访问不透明的响应,但是您仍然可以使用cache API缓存它们,并在service worker中的获取事件处理程序中使用它们进行响应。所以它们对于让你的应用脱机很有用,对于你不能控制的资源也很有用(例如,CDN上的资源没有设置CORS头)。


Consider the case in which a service worker acts as an agnostic cache. Your only goal is serve the same resources that you would get from the network, but faster. Of course you can't ensure all the resources will be part of your origin (consider libraries served from CDNs, for instance). As the service worker has the potential of altering network responses, you need to guarantee you are not interested in the contents of the response, nor on its headers, nor even on the result. You're only interested on the response as a black box to possibly cache it and serve it faster.

这就是{mode: 'no-cors'}的用途。


对于NodeJS应用程序也有解决方案。CORS Anywhere是一个NodeJS代理,它将CORS头添加到代理请求中。

指向代理的url从路径中提取,经过验证和代理。代理URI的协议部分是可选的,默认为“http”。如果指定443端口,则协议默认为“https”。

这个包对http方法或报头没有任何限制,除了cookie。不允许请求用户凭证。应用程序可以配置为需要一个头来代理请求,例如避免来自浏览器的直接访问。https://robwu.nl/cors-anywhere.html


javascript是一个有点棘手的答案,我通过从后端获得api,然后将其调用到前端来修复它。

public function get_typechange () {

    $ url = "https://........";
    $ json = file_get_contents ($url);
    $ data = json_decode ($ json, true);
    $ resp = json_encode ($data);
    $ error = json_last_error_msg ();
    return $ resp;

}