[英]Network request failed in react-native expo problem
我正在尝试从本地服务器获取数据,但我无法连接本地服务器。我面临“网络请求失败”
const testScreen= async ()=> {
await fetch("http://192.168.56.1:3000/comments")
.then((response)=>{
console.log(response.json())
})
.catch((error)=>{
console.log("sorry")
console.log(error)
})
}
...error..
Network request failed
at node_modules\whatwg-fetch\dist\fetch.umd.js:535:17 in setTimeout$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:383:16 in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue
at [native code]:null in callFunctionReturnFlushedQueue
确保服务器正在运行并且位于端口 3000 上。
此外,将“testScreen”function 更改为如下所示:
const testScreen = () => {
fetch("http://192.168.56.1:3000/comments")
.then(res => res.json())
.then((response) => {
console.log(response)
})
.catch((error)=>{
console.log("sorry")
console.log(error)
})
}
这可能与 CORS(跨域资源共享)问题有关。 在您的服务器端代码中启用 CORS。
除了 fetch 方法,您还可以使用其他一些库,例如 axios。
axios.get('http://192.168.56.1:3000/comments')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.