【问题标题】:How to fix the OpenWheather API's opaque response in RactiveJs with HTML5 Fetch API如何使用 HTML5 Fetch API 修复 RactiveJs 中 OpenWheather API 的不透明响应
【发布时间】:2017-02-10 13:08:04
【问题描述】:

这是我们第一次用Fetch HTML5 APIRactive JS弄脏我们的双手。

我们this code here 没有抛出任何错误。

注意 no-cors 标头设置为请求参数。

我们只需要从Open Weather Map guys获取免费的API数据。

如何使用 HTML5 Fetch API 修复 RactiveJs 中的不透明响应

【问题讨论】:

  • Notice the no-cors header set as the request parameter. - 这确保您的代码无法访问任何响应,这是您想要的吗?
  • @JaromandaX 不,先生,我们需要访问响应。我添加它来抑制错误:(
  • 抑制 cors 错误不会绕过 cors!看起来该 API 没有发出任何 cors 标头,因此您将无法直接通过浏览器访问该 API
  • @JaromandaX 那么先生还有什么可能呢?
  • 1.通过您自己的服务器代理。 2. API 是否支持 JSONP(在这种情况下您不会使用 fetch)...另一个问题是您没有正确使用 fetch。 fetch的结果是response object,然后你需要处理响应来获取数据

标签: javascript json ajax html ractivejs


【解决方案1】:

您的代码需要更正以下错误

  1. 使用api.openweathermaps.org 而不是sample.openweathermaps.org
  2. 使用GET 而不是POST
  3. 使用 VALID api 密钥(是的,您可以获得免费密钥)
  4. 正确使用 fetch

fetch('http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=**valid api key**', {
    method: 'GET',
    redirect: 'follow'
})
.then(response => response.json())
.then(data => console.dir(data));

【讨论】:

    猜你喜欢
    • 2017-07-25
    • 2020-02-17
    • 2018-08-19
    • 2018-07-21
    • 2017-09-07
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多