Ionic 5-API请求在浏览器上工作,而不是在模拟IOS上



我有一个Ionic 5/Capacitor应用程序,我正在对本地服务器进行API调用,该服务器运行在localhost:3000的docker上。当我从浏览器进行测试时,请求是可以处理的。邮差也要求罚款。在我的XCode日志模拟器中,我看到这个

[error] - ERROR {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"http://localhost:3000/pins","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost:3000/pins: 0 Unknown Error","error":{"isTrusted":true}}

真正有趣的部分是,我正在运行Fiddler来监控请求的发出。Fiddler也得到了200分,我甚至可以看到响应数据。因此,Fiddler看到了正确的网络呼叫,但随后我的Ionic应用程序出现了错误。这让我觉得这是一个Ionic/EEmulator/IOS问题,但我对Ionic不够熟悉,无法马上知道它是什么。

以下是负责提出请求的代码:

ngOnInit() {
const request = this.http.get('http://localhost:3000/pins');
this.refresh$.subscribe(
(lastPos: { latitude?: any; longitude?: number }) => {
request.subscribe(data => {
if (data) {
this.addMarkersToMap(data, lastPos);
}
});
}
);
}

构造函数中导入的HTTPClient来自Angular:

import { HttpClient } from '@angular/common/http';

我最终不得不使用这个包,检查我是否在移动设备上。

https://ionicframework.com/docs/native/http/

试试这个:

const request = this.http.get('http://localhost:3000/pins', { observe: 'response', withCredentials: true });

解决方案2:capacityor.config.json

"server": {
"hostname": "localhost",  (maybe try precising the port number too)
}

解决方案3:在您的Express服务器上(从https://ionicframework.com/docs/troubleshooting/cors)

const express = require('express');
const cors = require('cors');
const app = express();
const allowedOrigins = [
'capacitor://localhost',
'ionic://localhost',
'http://localhost',
'http://localhost:8080',
'http://localhost:8100'
];
// Reflect the origin if it's in the allowed list or not defined (cURL, Postman, etc.)
const corsOptions = {
origin: (origin, callback) => {
if (allowedOrigins.includes(origin) || !origin) {
callback(null, true);
} else {
callback(new Error('Origin not allowed by CORS'));
}
}
}
// Enable preflight requests for all routes
app.options('*', cors(corsOptions));
app.get('/', cors(corsOptions), (req, res, next) => {
res.json({ message: 'This route is CORS-enabled for an allowed origin.' });
})
app.listen(3000, () => {
console.log('CORS-enabled web server listening on port 3000');
});

最新更新