【问题标题】:Get response from a HTTP request in ionic从 ionic 中的 HTTP 请求中获取响应
【发布时间】:2020-10-17 15:29:47
【问题描述】:

如何在 ionic 中读取来自 http 请求的响应?我正在 ionic 中创建一个登录页面,并试图从 json 对象中的 php 代码中获取响应。我无法在 ionic 中抓取它返回来自后端的响应。

.ts 代码

this.http.post("http://localhost:83/api/v2/signin.php", JSON.stringify(this.credentials))
        .subscribe(data => {
          
          this.data = data;
          console.log(this.data);

          if(data.response=="success"){
            let toast = this.toastCtrl.create({
              message: 'Login was successfully',
              duration: 3000,
              position: 'top',
              cssClass: 'dark-trans',
              closeButtonText: 'OK',
              showCloseButton: true
            });
            toast.present();
           
            this.navCtrl.setRoot(HomePage);           
            this.storage.set("session",response);
            this.global.session=response;
          }else{
            this.global.loginState="login";
            let alert = this.alertCtrl.create({
              
              subTitle: data.response,
              buttons: ['OK']
            });
            alert.present();
          } 

登录失败时,控制台显示如下

Response {_body: "{"response":"Invalid login details entered"}"

成功我有以下

 Object { _body: "{\"response\":\"success\",
   \"data\":{\"id\":\"4\",\"name\":\"Eli James\",
   \"email\":\"eli_james@gmail.com\"}}",
  status: 200, ok: true, statusText: "OK",

我的php代码是这样的:

         if($row['email']==$email AND 
                 $row['status']=='1'){
       
                       $response=array(
                        "response"=>"success",
                        "data"=>array(
                            "id"=>$row['id'],
                            "name"=>$row['name'],                     
                            "email"=>$row['email']

                            )

                        );          
                      }else{
                    $response=array("response"=>"Invalid login details entered");
                     }
                   echo json_encode($response);

【问题讨论】:

    标签: php ionic-framework ionic3


    【解决方案1】:

    您正在从后端以string 的形式获得响应正文。您必须将正文解析为 JSON,然后使用它。

    只需将行从this.data = data; 更改为this.data = JSON.parse(data)

    this.data = JSON.parse(data._data);

    【讨论】:

      【解决方案2】:

      使用 post() 方法的观察选项告诉 HttpClient 你想要完整的响应:

      this.http.post("http://localhost:83/api/v2/signin.php", JSON.stringify(this.credentials), {观察: 'response') .subscribe(fullResponse => { .......

      现在 httpClient 返回一个 HttpResponse 类型的 Observable 而不仅仅是正文中包含的 JSON 数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-14
        • 2012-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-01
        • 2015-10-18
        相关资源
        最近更新 更多