【发布时间】:2021-05-25 11:30:14
【问题描述】:
我开发了一个Ionic React 应用程序,运行在Capacitor 之上。在浏览器(离子服务)中,应用程序运行完美。
当我在 Android emulator 上运行应用程序并尝试登录我的应用程序时,会显示 CORS 错误。
考虑到我无法更改 API 服务器后端,我该如何解决此错误。
在我的应用中,我使用 GET、POST 和 PUT 等不同方法联系外部 API。
浏览器使用 axios 的 POST 请求示例:
const doLogin = (e: any) => {
e.preventDefault();
const data = {
cardNr: cardNumber,
name: name,
};
axios
.post("/login", data)
.then((response) => {
//do sth
}
return response.data;
})
.catch((error) => {
console.log(error);
});
** 我无法在 API 后端进行更改。
我尝试了以下方法:
- 安装
cordova-plugin-advanced-http,根据https://ionicframework.com/docs/native/http/:它要求安装@angular/core,但我正在使用React。无论如何,即使安装了它,我也无法在Android上成功运行该应用程序,无法登录。
import { HTTP } from '@ionic-native/http/ngx';
const doLogin = (e: any) => {
e.preventDefault();
const data = {
cardNr: cardNumber,
name: name,
};
var http = new HTTP();
http
.post("https://xx/login", data, {})
.then((response) => {
//do sth
}
return response.data;
})
.catch((error) => {
console.log(error);
});
- 安装
@capacitor-community/http,根据https://github.com/capacitor-community/http:在这种情况下,当我导入‘import com.getcapacitor.plugin.http.Http’时会显示错误:‘Cannot resolve symbol http’。
import { Plugins } from "@capacitor/core";
const doLogin = (e: any) => {
e.preventDefault();
const data = {
cardNr: cardNumber,
name: name,
};
const { Http } = Plugins;
await Http.request({
method: "POST",
url: "https://xx/login",
data: data,
})
.then((response) => {
//do sth
}
return response.data;
})
.catch((error) => {
console.log(error);
});
任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: android reactjs ionic-framework capacitor capacitor-plugin