[英]Ionic React / Capacitor, requests work on web version and with postman but not on a device
I'm using axios to make requests to fetch the data from my external API (it's HTTP AWS server with ExpressJS and Nginx).我正在使用 axios 发出请求以从我的外部 API 获取数据(它是 HTTP AWS 服务器,带有 ExpressJS 和 Nginx)。 I tested it on my local machine with the web version of my Ionic app and everything is working expected.
我在本地机器上使用我的 Ionic 应用程序的 web 版本对其进行了测试,一切正常。 Also I can fetch data if I'm using my phone's browser.
如果我使用手机的浏览器,我也可以获取数据。
Same goes with postman, I can fetch data without any problems. postman 也是如此,我可以毫无问题地获取数据。
The only place where these requests don't work is the actual device.这些请求不起作用的唯一地方是实际设备。 Looking at the Android Studio console the error is: "Msg: Network Error" (failing to figure out how to get more from axios error object).
查看 Android Studio 控制台,错误是:“消息:网络错误”(无法弄清楚如何从 axios 错误对象中获取更多信息)。
I configured CORS following the official Ionic documentation.我按照官方 Ionic 文档配置了 CORS。 I've set all needed origins and options (can't use * origin because I have to use credentials with my requests).
我已经设置了所有需要的来源和选项(不能使用 * origin 因为我的请求必须使用凭据)。 Express configuration looks like this:
Express 配置如下所示:
const corsOptions = {
origin: [
'http://localhost:8100',
'http://localhost:8080',
'http://localhost',
'capacitor://localhost',
'ionic://localhost',
],
credentials: true,
optionsSuccessStatus: 200,
exposedHeaders: ["set-cookie"]
}
// Enable preflight requests for all routes
app.options('*', cors(corsOptions));
app.use(cors(corsOptions));
On the client (request example):在客户端(请求示例):
try {
const response = await axios('http://my.api.url', {
method: 'get',
withCredentials: true,
headers: {
'Accept': 'application/json'
}
});
const data = response.data;
// Do something with the data
} catch(error) {
console.log(error);
};
I think it has something to do with Capacitor, maybe there is a problem with non-https API (but then the question is why does it work with the web version).我认为它与Capacitor有关,也许非https API有问题(但问题是为什么它适用于web版本)。 I tried disabling credentials for my requests but the error reoccur.
我尝试为我的请求禁用凭据,但错误再次发生。 Also removing Nginx doesn't seem to change anything.
同样删除 Nginx 似乎并没有改变任何东西。
Update: Also the axios says the request is sent but the server didn't respond.更新:axios 也表示请求已发送,但服务器没有响应。
I sorted it out, I had to do following.我整理好了,我必须做以下事情。
Had to add a SSL to my web server (I used letsencrypt).必须将 SSL 添加到我的 web 服务器(我使用了letsencrypt)。
Had to add this to capacitor.config.json:必须将此添加到电容器.config.json:
"server": { "allowNavigation": [ "my.api.url" ] } “服务器”:{“allowNavigation”:[“my.api.url”]}
Official Capacitor Documentation - Common Configuration 电容器官方文档 - 常用配置
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.