离子POST:响应是一个字符串而不是JSON

时间:2018-08-06 10:01:36

标签: angular typescript post ionic-framework ionic3

我正在尝试开发一个简单的应用程序以在Ionic和Ionic上工作。

该应用程序包含一个简单的按钮,用于启动蓝牙并使用功能 startScanning()向我的服务器发送发布请求。

首先,我认为这是服务器端的问题,因此我尝试通过POSTMAN软件进行POST。
结果是完美的,响应是JSON。

所以我认为这与我的打字稿代码有关,您能帮帮我吗?

我的代码:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { BLE } from '@ionic-native/ble';
import { HTTP } from '@ionic-native/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  static readonly SERVER_ADDRESS  = 'https://www.example.com';
  lock: any;
  randomFound:boolean;
  readChar:any;
  notifyChar:any;
  authenticationState: any;
  writeChar:any;

  constructor(public navCtrl: NavController, private ble: BLE, private http: HTTP) {

  }


  startScanning(){

    this.authenticationState = 0;
    this.ble.startScan([]).subscribe( device => {
      console.log(device.name);

      let patt = /\d\d-\d\d-\d\d-\d\d/;
      if( patt.test(device.name)){
        console.log("Trying to connect..");
        this.ble.connect(device.id).subscribe(peripheralData => {
          this.randomFound = false;
          console.log("Connected");
          for(let char of peripheralData.characteristics){
            console.log("CHAR : " + char.characteristic);

            //this.characteristics.push(char);
            if(char.characteristic.indexOf("6E400005") != -1){
              console.log("Read char found");
              this.readChar = char;
            }
            if(char.characteristic.indexOf("6E400003") != -1){                                 
              console.log("Notify char found");
              this.notifyChar = char;
              this.ble.startNotification(device.id,this.notifyChar.service, this.notifyChar.characteristic).subscribe(value =>{
                console.log("Value changed ");
                let data1 = new Uint8Array(value);
                if(this.authenticationState == 0){             
                  if(this.randomFound == false){
                    this.randomFound = true;

                    let random = this.buf2hex(data1);
                    console.log("Random " + random);

                    //var postData = JSON.stringify({lock:device.name,random:this.buf2hex(data)});
                    var postData = {lock:device.name,random:this.buf2hex(data1)};
                    let headers:any = {
                      'Content-Type': 'application/json'
                    };
                    console.log("Post Data " + postData);
                    this.http.setDataSerializer('json');
                    this.http.post(HomePage.SERVER_ADDRESS+'/external/RequestAccessService',postData, headers).then(
                      data => {

                        //let test = data.data.json() as Object;
                        //console.log("Response " + test);
                        console.log("Response Json " + data.data.json);
                        let key:ArrayBuffer = new ArrayBuffer(20);
                        let keyView:Uint8Array = new Uint8Array(key);
                        //let key:Array<any> = this.parseHexString(data.data);
                        let buf:any = this.parseHexString(data.data);
                        //let buf:any = this.parseHexString(data._body);
                        console.log("BUF " + buf);
                        for(let i=0;i< 20;i++){
                          keyView[i] = buf[i];
                        }

                        console.log("KEY " +keyView);
                        this.ble.writeWithoutResponse(device.id,this.writeChar.service,this.writeChar.characteristic,key).then(()=>{
                          console.log("Request to open lock sent...");
                          this.authenticationState = 1;
                          this.ble.read(device.id,this.readChar.service,this.readChar.characteristic).then( 
                            (data) =>{
                              console.log(this.buf2hex(data));

                          }, (err) =>{
                            console.log("Error Reading" + err);
                          }

                          );               

                        }, (err) => {
                          console.log("Error " + err);
                        });

                      }).catch(error =>{
                        console.log(error.status);
                        console.log(error.error);
                        console.log(error.headers);
                      })

                  }


                }else{
                  console.log("Waiting for status");
                  console.log(this.buf2hex(data1));
                  if(data1[0] == 0x01){
                    console.log('the bike is unlocked, enjoy the ride!');

                  }else{
                    console.log('Not authorized to use the bike!');

                  }

                  this.ble.stopNotification(device.id,this.notifyChar.service,this.notifyChar.characteristic).then( ()=>{
                    console.log("Notification stopped");
                  });

                }



              } );



            }
        if(char.characteristic.indexOf("6E400002") != -1){
          console.log("Write char found");
          this.writeChar = char;
        }


      }
        })
      }
    });

    setTimeout( () => {
      this.ble.stopScan().then( () =>{
        console.log("scanning has stopped");


      });
    },3000);


  }

  buf2hex(buffer){
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
  }

  parseHexString(str) { 

    var lower = str.toLowerCase();
    var result = [];
    while (lower.length >= 2) {
        var t = lower.substring(0, 2);
        console.log("STR " + t + " INT " + parseInt(t,16));
        result.push(parseInt(lower.substring(0, 2), 16));
        lower = lower.substring(2, lower.length);
    }

    return result;
  }

}


离子框架:3.9.2
Ionic应用程序脚本:3.1.11
角核:5.2.11
Angular编译器CLI:5.2.11
节点:8.11.1
操作系统平台:Windows 10
导航器平台:iPhone

谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

select lotid, count(*) as stephandles
from lotflow_d d
where eqptype not in ('CUDDFINP','CUBDFINP','BDFINP','DDFINP','CUDFSEM', 'DFSEM',
                      'SORT','CUSORT','CUNPURGE','NPURGE','EDFINP','CUEDFINP')
and not exists
(
  select *
  from lotmove_r r
  where r.lotid = d.lotid
    and r.stephandle >= d.stephandle
    and r.stephandle not like '%8888%'
    and r.stephandle like '%.%.%'
    and r.qtap_group in ('8685','8686','8687','8688','8689','8533',
                         '8532','2534','2533','8684','8690')
    and r.datadate > sysdate-3
    and r.priority <= 5
    and r.subplanid not like '%RWK%'
)
group by lotid
order by lotid;

您只需要对您的响应字符串做JSON.parse,就可以将其作为post方法调用的响应,就可以像JSON格式一样希望对您有所帮助。