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))

推荐答案

Opaque Responses

对跨域资源的no-cors请求的响应为response type of 'opaque'.如果在try 将其转换为JSON之前记录响应,您将看到一种类型的"不透明".

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

不透明过滤响应是一种过滤响应,其类型为"不透明",url列表为空列表,状态为0,状态消息为空字节序列,标题列表为空,正文为空,尾部为空.

They cannot currently be read when the type is opaque as explained on Google's docs on the opaque type.

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.

Enable CORS support on your server

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 documentation on CORS requestsAccess-Control-Allow-Origin.

An example in PHP:

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

Json相关问答推荐

JOLT拉平数组

JSON:将项';S键/名称移动到属性中,并使用JQ将其转换为数组

如何用JQ更改空/布尔/数字的 colored颜色 ?

有没有办法让serde_json正确/不正确地处理NaN、inf和-inf(IEEE 754特殊标准)?

如何使用jq使用子值对象的键对json对象进行分组

Powershell ConvertFrom-Json 意外地从包含字符串的单个项目数组生成字符串而不是对象数组

将 std::可选值存储到 json 文件 C++

为什么 Django Rest API 序列化器没有正确序列化多对多字段

Spark-SQL中的from_unixtime函数未能给出正确的输出

将JSON行转换为TSV格式, for each 数组项生成单独的行

取消嵌套数组并将数组名称添加为附加字段

从 JSON 响应中获取最新版本发布字段

如何在 onClick 事件处理程序中识别在同一 map 上绘制的多个多边形中的哪个(使用 react-leaflet)被单击?

Angular 2/Web Api - json 解析错误语法错误意外结束输入

如何使用 Jackson 定义可选的 json 字段

将json字符反序列化为枚举

如何在java中比较来自JsonObject的空值

Select 什么数据类型json或者jsonb或者text

有没有办法使用 Jackson 将 Map 转换为 JSON 表示而不写入文件?

将 Pandas 数据框转换为嵌套 JSON