在 Android Emulator 上运行应用时,如何在 Ionic React 应用中使用社区 HTTP 插件?

问题描述

我正在开发一个运行在 Capacitor 之上的 Ionic React 应用程序。它适用于浏览器中的 axios 请求,但在 Android 上我有 CORS 问题,这就是我使用 community HTTP plugin 的原因:https://github.com/capacitor-community/http

示例:我点击了我的登录按钮。我的电子邮件和密码等数据应该通过 HTTP post 发送,但它捕获了我在那里放置的错误:再试一次。

你知道它为什么会发生吗?

也没有关于 Android Studio 请求的错误日志。只有这些:

    /system_process E/ClipboardService: Denying clipboard access to com.google.android.googlequicksearchBox,application is not in focus nor is it a system service for user 0
    E/netmgr: qemu_pipe_open_ns:62: Could not connect to the ‘pipe:qemud:network’ service: Invalid argument
    E/netmgr: Failed to open QEMU pipe ‘qemud:network’: Invalid argument
    E/wifi_forwarder: qemu_pipe_open_ns:62: Could not connect to the ‘pipe:qemud:wififorward’ service: Invalid argument
    E/wifi_forwarder: RemoteConnection Failed to initialize: RemoteConnection Failed to open pipe

为了解决这些错误,我在 application 元素中添加了此设置:

    android:usesCleartextTraffic=“true”

错误仍然发生。

Android 模拟器已连接到 Internet。

<!-- Permissions -->
    <uses-permission android:name="android.permission.INTERNET" />
 <!-- Network API -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

登录.tsx:

import React from "react";
import { useHistory } from "react-router-dom";
import { useState,useContext } from "react";
import MyContext from "../my-context";
import {
  IonPage,IonHeader,IonContent,IonButton,IonInput,IonLabel,IonItem,IonGrid,IonCol,IonAlert,} from "@ionic/react";
import { Http,HttpResponse } from "@capacitor-community/http";

const Login = () => {
  const history = useHistory();
  const {
    email,setEmail,password,setPassword
  } = useContext(MyContext);

     const doLogin = async (e: any) => {
    e.preventDefault();

    const loginData = {
      email: email,password: password,};

    //https://github.com/capacitor-community/http
    const options = {
      url: "https://xx/login,data: loginData,};
    const response: HttpResponse = await Http.post(options)

      .then((response) => {

        if (response.data.token) {
          history.push("/home");
          window.location.reload();
        }
        return response.data;
      })
      .catch((error) => {
        setMessage(
          "Try again!"
        );
      setIserror(true);
      });
    };

return (
    <IonPage>
      <IonContent className="ion-padding ion-text-center">
        <IonGrid>
          <IonRow>
            <IonCol>
              <IonAlert
                isOpen={iserror}
                onDiddismiss={() => setIserror(false)}
                header={"Info!"}
                message={message}
                buttons={["Ok"]}
              />
            </IonCol>
          </IonRow>
         
                <h1>Login</h1>
              </IonCardTitle>
          
              <IonItem>
                <IonLabel position="floating">Email</IonLabel>
                <IonInput
                  name="email"
                  type="email"
                  value={email}
                  onIonChange={(e) => setEmail(e.detail.value!)}
                />
              </IonItem>

              <IonItem>
                <IonLabel position="floating">Password</IonLabel>
                <IonInput
                  name="password"
                  type="password"
                  value={password}
                  onIonChange={(e) => setPassword(e.detail.value!)}
                />
              </IonItem>
             
              <IonButton onClick={doLogin}>Login</IonButton>
             
        </IonGrid>
      </IonContent>
    </IonPage>
  );
};

export default Login;

我从 3 天起就一直被这个问题困扰,所以任何帮助都会非常非常感激。谢谢!

解决方法

服务器是否收到了 HTTP 请求?您可以尝试打印日志以供判断。

这样我们就可以进行下一步了

,

对于任何感兴趣的人,我找到了解决方案。在此文档 https://github.com/capacitor-community/http 中,Android 配置 缺失。

1- 因此,在 add http plugin

中导入和 android\app\src\main\java\\MainActivity.java
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

我根据自己的需要编写了请求,现在它完美无缺。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...