Ionic网络请求(解决跨域和参数序列化的问题)

Ionic   -v  3.20.0

Node  -v   8.9.1

Cordova -v 8.0.0

Angular 4

import {ChangeDetectorRef, Component, Injectable} from '@angular/core';
import {HttpClient,HttpHeaders} from "@angular/common/http";

/**
 * Generated class for the AddressSelectPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Injectable()
export class HttpService {
  httpurl='http://192.168.1.8:8080/CarRental/';//你的服务器地址前缀
  constructor(public http: HttpClient) {

  }

  GET(urlmethod , callback ?: (res: any, error: any) => void): void  {
    this.http.get('' + this.httpurl + '' + urlmethod + '').subscribe(data =>
      { callback && callback(data, null);},
      err =>{callback && callback(null, err);}
    )
  }



  //Common post method  post请求参数序列化
  POST(data, urlmethod , callback ?: (res: any, error: any) => void): void  {
    // let headers = new Headers({
    //   'Content-Type': 'application/x-www-form-urlencoded'
    // });
    const headers = new HttpHeaders().set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
      this.http.post('' + this.httpurl + '' + urlmethod + '', this.toQueryString(data), {headers})
        .subscribe(data =>
        { callback && callback(data, null);},
            err =>{callback && callback(null, err);}
        )
  }
  //Common post method  post可以提交json参数,参数没有使用toQueryString序列化
  POST2(data, urlmethod , callback ?: (res: any, error: any) => void): void  {
    // let headers = new Headers({
    //   'Content-Type': 'application/x-www-form-urlencoded'
    // });
    const headers = new HttpHeaders().set("Content-Type", "application/json;charset=utf-8");
    this.http.post('' + this.httpurl + '' + urlmethod + '', data, {headers})
      .subscribe(data =>
        { callback && callback(data, null);},
        err =>{callback && callback(null, err);}
      )
  }

  POSTForm(data, urlmethod, callback ?: (res: any, error: any) => void): void   {

    const headers = new HttpHeaders().set("Content-Type", "multipart/form-data; charset=utf-8");
    //const headers = new HttpHeaders().set("Content-Type", "application/x-www-form-urlencoded");
     this.http.post('' + this.httpurl + '' + urlmethod + '', data, {})
      .subscribe(data =>
        { callback && callback(data, null);},
        err =>{callback && callback(null, err);}
      )
  }

  //post请求参数序列化
  // POST(data, urlmethod) {
  //
  //   const headers = new HttpHeaders().set("Content-Type", "application/x-www-form-urlencoded");
  //   return this.http.post('' + this.httpurl + '' + urlmethod + '', this.toQueryString(data), {headers})
  //     .map(res => res);
  // }
  //参数序列化
  private toQueryString(obj) {
    let result = [];
    for (let key in obj) {
      key = encodeURIComponent(key);
      let values = obj[key];
      if (values && values.constructor == Array) {
        let queryValues = [];
        for (let i = 0, len = values.length, value; i < len; i++) {
          value = values[i];
          queryValues.push(this.toQueryPair(key, value));
        }
        result = result.concat(queryValues);
      } else {
        result.push(this.toQueryPair(key, values));
      }
    }
    return result.join('&');
  }
  //参数序列化
  private toQueryPair(key, value) {
    if (typeof value == 'undefined') {
      return key;
    }
    return key + '=' + encodeURIComponent(value === null ? '' : String(value));
  }

}

猜你喜欢

转载自blog.csdn.net/qq_31384551/article/details/80236378
今日推荐