【发布时间】:2019-06-04 03:38:53
【问题描述】:
我有一个使用 NodeJS 后端的 React-Native 应用程序,该后端提供 API。
我的 React-Native 前端正在使用 Expo 和 Axios 来访问我的 NodeJS API 路由(使用 Hapi、Joi、Knex),这将(例如)更新我的数据库(MySQL)。
我的 iOS 模拟器一切正常。但是,在 Android Emulator 上,我在路线“不起作用”上的一些点击带有以下错误消息:Network Error - node_modules/axios/lib/core/createError.js:16:24 in createError(实际上,它起作用了,但前面没有检测到它......)
这很奇怪,因为就像我说的,这仅适用于我的某些路线。我将http://localhost:8000/api 更改为http://10.0.2.2:8000/api 以确保Android Emulator 可以访问我的API,这部分没问题。
有问题的路线在 iOS 上运行正常,在 Insomnia / Postman (localhost:8000/api/sendMail) 上运行正常。它在 Android Emulator 上运行,但应用程序未检测到它。
这是我的代码示例:
FRONT -- 按下我的“SendEmail”按钮:
/* Button.js */
const sendAndEmailPromise = await sendEmail(this.state.email);
console.log(sendAndEmailPromise); // Output : NOTHING (not undefined, not null, N O T H I N G).
if (sendAndEmailPromise.status === 200) {
// handle it
} else (sendAndEmailPromise.status === 403) {
// etc. for each of my codeStatus that can be returned by my API
}
/* MyAPI.js */
export function sendEmail(mail) {
return axiosInstance
.post(`/sendEmail`, null, {
params: {
mail
},
})
.then(response => response) // Will not enter here
.catch(error => {
console.log(error); // Will output : NETWORK ERROR
});
}
BACK -- 这是 sendEmail 的承诺:
// Will return true of false :
const isMailSend = await sendTheEmail(mail);
console.log(isMailSend); // Output : TRUE and I receive the email on my gmail, so Android Emulator HIT the route.
if (isMailSend) {
return handler
.response({
data: {
message: "Email sent.",
},
})
.code(200);
} else {
// Handle it and return another response
}
我希望我现在一切正常(实际上发生了......)并获得代码状态,而不是“网络错误”。
更多,Axios 是否有可能得到另一个级别的错误?更具体的东西。
一个 GitHub 问题,虽然不完全相同,但似乎与等价的东西相关:https://github.com/axios/axios/issues/973
谢谢。
【问题讨论】:
-
您是否在设备上尝试过您的服务器外部 ip 而不是使用 localhost 域?设备上的 localhost 肯定不会工作。 Axios 在 android 上 100% 运行,因为我在多个项目中使用它。
-
感谢您的回复。为什么你的意思是“外部IP”?现在,我在安卓模拟器上使用
http://10.0.2.2:8000/api(而不是localhost)。路由调用正在工作(因为发送了邮件),但是,它进入 catch() 并出现一般错误......谢谢您的时间。 -
external ip 我的意思是你当前用于全局访问的服务器 ip (ipv4)。如果它在本地主机中,您必须使用您的服务器 ip,这可能类似于 192.168.1.1,例如您使用的是什么操作系统?
-
如果您的服务器在您的机器上运行,则使用它来查找您的本地 IP whatismybrowser.com/detect/what-is-my-local-ip-address
-
我在 MacOS Mojave 上使用 EXPO 运行它。当我尝试使用 Postman 访问我的 IPV4(首选项 > 网络 > 192.168.63.141)时,我得到了:
"Error: Couldn't connect to server"
标签: react-native axios react-native-android expo