简体   繁体   English

在 Android 模拟器上运行 React 应用程序时如何修复 CORS 错误?

[英]How to fix CORS error when running the React app on Android emulator?

I have developed an Ionic React app, running on top of Capacitor .我开发了一个Ionic React应用程序,运行在Capacitor之上。 In browser (ionic serve), the app runs perfectly.在浏览器(离子服务)中,应用程序运行完美。 When I run the app on Android emulator and I try to log in my App, a CORS error is shown.当我在Android emulator上运行该应用程序并尝试登录我的应用程序时,会显示CORS 错误 How can I solve this error, taking in consideration that I cannot change the API server back end.考虑到我无法更改 API 服务器后端,我该如何解决此错误。 In my app I'm contacting an external API using different methods such as GET, POST and PUT.在我的应用程序中,我使用 GET、POST 和 PUT 等不同方法联系外部 API。

an example of a POST Request with axios for browser:一个带有 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);
    });

** I cannot make changed in API back-end. **我无法在 API 后端进行更改。

I have tried the following:我尝试了以下方法:

  1. install cordova-plugin-advanced-http , according to https://ionicframework.com/docs/native/http/ : It requests to install @angular/core , but I'm working with React.根据https://ionicframework.com/docs/native/http/安装cordova-plugin-advanced-http :它要求安装@angular/core ,但我正在使用 React。 Anyway, even after installing it, I cannot run the app successfully on Android, cannot login.无论如何,即使安装后,我也无法在 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);
    });
  1. install @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' . install @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);
    });

Any help would be really appreciated.任何帮助将非常感激。 Thank you!谢谢!

A fast fix could be to set the header of the post request to something which doesn't trigger a cors request, eg "Content-Type": "application/x-www-form-urlencoded" .快速修复可能是将发布请求的 header 设置为不会触发 cors 请求的内容,例如"Content-Type": "application/x-www-form-urlencoded"

Those requests are called "simple requests" and you can read up on them here .这些请求称为“简单请求”,您可以在此处阅读它们。

Sometimes the owner of the server add Origins in allowed origins so that only those origins can call the APIs, probably your website/local URL doesn't matches with the allowed origins,有时,服务器的所有者在允许的来源中添加 Origin,以便只有这些来源可以调用 API,可能您的网站/本地 URL 与允许的来源不匹配,

For anyone interested, I found the solution.对于任何感兴趣的人,我找到了解决方案。 In this doc https://github.com/capacitor-community/http , configuration for Android is missing .在此文档https://github.com/capacitor-community/http中,缺少 Android 的配置

1- So, import and add http plugin in android\app\src\main\java\MainActivity.java 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- Sync gradle files in Android Studio: 2- 在 Android Studio 中同步 gradle 文件:

File --> Sync Project with Gradle Files

I wrote the http request according to my needs and now it works perfectly.我根据我的需要编写了 http 请求,现在它可以正常工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 运行 Android 模拟器时如何修复 GPU Driver Issue 错误 - How to fix GPU Driver Issue error when running the Android emulator 如何在具有Android Q的Android模拟器上运行flutter应用程序时解决“ HttpException”错误? - How to fix 'HttpException' error while running flutter app on an Android Emulator with Android Q? 在 Android 模拟器上运行应用程序时,如何在 Ionic React 应用程序中使用社区 HTTP 插件? - How to use community HTTP plugin in a Ionic React app when running the app on Android Emulator? 在模拟器上运行Android应用时出错 - Error in running Android app on Emulator Android模拟器-运行android应用时出现错误 - Android Emulator -Error comes when running android app 在模拟器上运行我的 android 应用程序时遇到错误 - Facing an error when running my android app on an emulator Android 模拟器未与我的 React Native 应用程序一起运行 - Android emulator not running with my React Native App 在Android模拟器上运行应用程序时出错 - Error while running app on android emulator 如何在反应原生应用程序中显示复选框? 在 android 仿真器中可见时 - How to show the checkbox in the react native app? When it is visible in android emulator 在Android模拟器中运行应用程序时出错 - Error while running app in android emulator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM