问题描述
我正在使用 fetch() 从 api 服务器获取数据.我的错误如下所示:
I am using fetch() to grab data from api server. My error looks like this:
Uncaught (in promise) SyntaxError: Unexpected end of input at
fetch.then.blob.
你能告诉我我做错了什么吗?
Can you please tell me what am I doing wrong.
const weatherAPi ='https://www.metaweather.com/api/location/523920';
fetch(weatherAPi, {
mode: 'no-cors'
}).then(blob => blob.json())
.then(data => console.log(data))
推荐答案
不透明的响应
对跨域资源的 no-cors
请求的响应具有 不透明"的响应类型.如果您在尝试将其转换为 JSON 之前记录响应,您将看到一种不透明"类型.
OpaqueResponses
A response for a no-cors
request to a cross-origin resource has a response type of 'opaque'. If you log the response before trying to turn it to JSON, you will see a type of "opaque".
不透明类型被列为严格限制"whatwg.org 上的 fetch 规范中解释了.
Opaque types are listed as "severely restricted" as explained in the fetch spec on whatwg.org.
不透明过滤响应是一个过滤响应,其类型为不透明",url列表为空列表,状态为0,状态消息为空字节序列,头部列表为空,正文为空,尾部为空.
An opaque filtered response is a filtered response whose type is "opaque", url list is the empty list, status is 0, status message is the empty byte sequence, header list is empty, body is null, and trailer is empty.
当类型不透明时,当前无法读取它们,如 Google 关于 opaque 类型的文档.
They cannot currently be read when the type is opaque as explained on Google's docs on the opaque type.
不透明响应是针对不返回 CORS 标头的不同来源的资源发出的请求.对于不透明的响应,我们将无法读取返回的数据或查看请求的状态,这意味着我们无法检查请求是否成功.使用当前的 fetch() 实现,不可能从窗口全局范围请求不同来源的资源.
An opaque response is for a request made for a resource on a different origin that doesn't return CORS headers. With an opaque response, we won't be able to read the data returned or view the status of the request, meaning we can't check if the request was successful or not. With the current fetch() implementation, it's not possible to make requests for resources of a different origin from the window global scope.
在您的服务器上启用CORS支持
这可以取决于环境或语言.例如,您可以通过更改服务器配置来更改 Nginx 环境中的 CORS 设置,或者您可以在应用程序代码(例如 PHP)中指定标头.
EnableCORSsupportonyourserver
This can be environment-dependent or language-dependent. For example, you can change CORS settings within Nginx's environment by changing your server config, or you can specify headers within your application code such as in PHP.
我强烈建议阅读 Mozilla 关于 CORS 请求的文档 以及 Access-Control-Allow-起源.
I highly recommend reading the Mozilla documentation on CORS requests and also Access-Control-Allow-Origin.
PHP 中的一个例子:
An example in PHP:
<?php
header("Access-Control-Allow-Origin: *"); // "*" could also be a site such as http://www.example.com
这篇关于fetch() 输入意外结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!