fetch()输入意外结束 [英] fetch() unexpected end of input

查看:155
本文介绍了fetch()输入意外结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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))


推荐答案

不透明响应


对跨域资源的无要求请求的响应具有不透明的响应类型。如果您在尝试将响应转换为JSON之前记录了响应,则会看到一种不透明的类型。

Opaque Responses

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上的获取说明中所述。

Opaque types are listed as "severely restricted" as explained in the fetch spech on whatwg.org.


不透明的已过滤响应是类型为 opaque的已过滤响应,URL列表为空列表,状态为0,状态消息为空字节序列,标头列表为空,正文为null,预告片为空。

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文档

一个不透明的响应是针对不同来源的资源请求,该资源不返回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 on a different origin from the window global scope.


启用CORS支持


最可能解决此问题的方法是在服务器上启用CORS请求支持。这可以取决于环境或取决于语言。例如,您可以通过更改服务器配置来在Nginx的环境中更改CORS设置,也可以在应用程序代码(例如PHP)中指定标头。

Enable CORS support

The most likely solution to your problem is to enable CORS request support on your server. This can be environment dependant or language dependant. 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.

我强烈建议阅读有关CORS请求的Mozilla文档

PHP中的示例:

<?php
header("Access-Control-Allow-Origin: *");  // "*" could also be a site such as http://www.example.com

这篇关于fetch()输入意外结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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