![](/img/trans.png)
[英]How to fix GPU Driver Issue error when running the Android emulator
[英]How to fix CORS error when running the React app on Android emulator?
我開發了一個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
:它要求安裝@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
, according to https://github.com/capacitor-community/http : in this case, when I import 'import com.getcapacitor.plugin.http.Http'
it shows an error: '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);
});
任何幫助將非常感激。 謝謝!
快速修復可能是將發布請求的 header 設置為不會觸發 cors 請求的內容,例如"Content-Type": "application/x-www-form-urlencoded"
。
這些請求稱為“簡單請求”,您可以在此處閱讀它們。
有時,服務器的所有者在允許的來源中添加 Origin,以便只有這些來源可以調用 API,可能您的網站/本地 URL 與允許的來源不匹配,
對於任何感興趣的人,我找到了解決方案。 在此文檔https://github.com/capacitor-community/http中,缺少 Android 的配置。
1-因此,在 android\app\src\main\java\MainActivity.java 中導入並添加 http 插件
package com.myapp.com;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.Plugin;
import java.util.ArrayList;
import com.getcapacitor.plugin.http.Http; //added
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initializes the Bridge
this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
// Additional plugins you've installed go here
// Ex: add(TotallyAwesomePlugin.class);
add(Http.class); //added
}});
}
}
2- 在 Android Studio 中同步 gradle 文件:
File --> Sync Project with Gradle Files
我根據我的需要編寫了 http 請求,現在它可以正常工作了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.