【问题标题】:Fetch API request only returns null [duplicate]Fetch API 请求仅返回 null [重复]
【发布时间】:2017-10-07 04:01:33
【问题描述】:

我正在了解Fetch API 以及如何使用它。但是,当我使用有效的 json 向 this page 发出请求时,响应会返回 null。我在 codepen.io 上提出这个请求,所以我知道这涉及 CORS。

const headers = new Headers();
const params = {
    method: 'GET',
    headers : headers,
    mode : 'no-cors'
}

const request = new Request( 'http://api.forismatic.com/api/1.0/method=getQuote&format=json&lang=en' );

fetch(request, params).then(function( response ){
    return response;
}).then( function( json ){
    console.dir(json.body);
});

开发工具中的请求返回:

Response
body : null
bodyUsed : false
headers :Headers
ok:false
redirected : false
status : 0
statusText : ""
type: "opaque"
url :""

来自 MDN:

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

所以我想知道为什么我的请求中没有添加响应正文,我需要更改/添加什么来获取请求的 JSON 的内容?

【问题讨论】:

  • 因为您使用的是 no-cors 模式。这就是它的作用:允许提出请求但不允许得到响应。
  • 当我将 method 更改为 cors 时,我在控制台中得到了这个。 Fetch API cannot load http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' 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.
  • 您的主要问题是/将是 CORS - API 似乎不允许 CORS,因此您不能在页面中“借用”他们的资源 - 您需要一个服务器端方法来代表您的网页访问该 API

标签: javascript json ecmascript-6


【解决方案1】:

这是对使用 no-cors 问题的参考。目前这似乎不适用于全局窗口对象。通过 Postman 可以正常工作。

no-cors with fetch

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 2019-11-03
    • 2021-06-13
    • 2020-04-28
    • 2020-06-01
    相关资源
    最近更新 更多