【发布时间】:2016-06-22 21:04:18
【问题描述】:
我正在尝试在我的 react-native 应用程序中获取()一些数据,但它失败了。因此,我找到了 NetInfo,并在应用程序启动时使用它,并且在每个 MapView onRegionChangeComplete 事件上使用 iOS 模拟器(如果重要,iPhone5s 和 iPhone 6),NetInfo 返回的状态每次都是 unknown。 MapView 工作正常,我可以在模拟器上使用 Safari 浏览网络。我发现与 fetch() 失败相关的最常见问题是开发人员在其 url 中使用 localhost。我正在使用http://api.openweathermap.org/data/2.5/weather?作为我的网址,所以我相信这是一个模拟器问题。我没有要测试的 iOS 设备,而且 MapView 还不能用于 android,所以我不能在 android 上测试。有人可以为我指出正确的方向吗?
谢谢。
PS。我记录到控制台的获取错误是 - TypeError: Network request failed
这是我的代码:
module.exports = function(latitude, longitude) {
var rootURL = 'http://api.openweathermap.org/data/2.5/weather?APPID=MYAPIKEY&lat=35&lon=139';
console.log(rootURL);
return fetch(rootURL) // fetch is part of react or react-native, no need to import
.then(function(response){ // method chaining used here
// Shorthand to check for an HTTP 2xx response status.
// See https://fetch.spec.whatwg.org/#dom-response-ok
if (response.ok) {
console.log('Response from fetch was ok, returning response to next then');
return response
} else {
// Raise an exception to reject the promise and trigger the outer .catch() handler.
// By default, an error response status (4xx, 5xx) does NOT cause the promise to reject!
console.log('Throwing error to .catch with statusText: ' + response.statusText);
throw Error(response.statusText);
}
})
.then(function(response) {
console.log('Returning JSON to next then')
return response.json();
})
.then(function(json) { // chain a second function when JSON is returned
console.log('Returning this json to Api call in index.os.js' + json);
return {
city: json.name,
//temperature: kelvinToF(json.main.temp),
//decription: json.weather[0].description
}
})
.catch(function (error) {
console.log('My fetch Error: ' + error + 'Specific error: ' + error.message);
})
}
第二次更新:除了下面的更新和信息之外,我已将其缩小到这是一个 iOS 模拟器问题。我在安卓设备上没有同样的问题。再次 - 模拟器唯一的问题是使用 http: url 发出 fetch() 请求。当我使用 https: url 时,模拟器很高兴。我还在模拟器中发现了一些 DEV 设置以允许 http 请求。这没有给我任何改变。
更新:我已将问题缩小到 url。如果我在 react-native 中使用 fetch,这个 url http://api.openweathermap.org/data/2.5/weather?APPID=MYAPPKEY&lat=35&lon=139 和 MYAPPKEY 等于我的密钥,它会失败。如果我在浏览器中使用相同的 url,它会返回我期望的 json。
另外,如果我在 react-native 中使用 fetch 并使用这个 url https://api.github.com/users/mralexgray/repos,我没有得到 Network request failed,我得到了有效的 json。
还有一个有趣的提示——如果我在浏览器中输入 openweathermap url,地址栏会在返回 json 时去掉 http:// 部分。当我在浏览器中输入github地址时,地址栏保持https://。
另一个有趣的注意事项 - 如果我使用非 https url,它会失败。
【问题讨论】:
-
你应该至少提供一些代码
-
我认为这不是代码问题。我已经在“更新:”下更新了我的问题。
-
可能是iOS ATS机制的原因,请尝试禁用它。 stackoverflow.com/questions/31254725/…
-
谢谢。那是正确的答案!如果您想要更多信誉,请随意将其作为官方答案!
标签: react-native fetch