1

I have an ionic 3 project and I'm trying to have a post request. Up till now I have been using the following code that was working well:

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import {HttpParams} from '@angular/common/http';
import { Observable, Subscription } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';

@Injectable()
export class Need4CarGateway {
  token = "";
  availabilityPeriod="00:00";
  private sub: Subscription;


  constructor(public http: Http, private logger:Logger,private utils:Utils) {
  }


  myPostRequest(){
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded' );
    headers.append('Authorization', 'Bearer '+mytoken);
    headers.append('access_token', ACCESSTOKEN );
    let options = new RequestOptions({ headers: headers });

    let body = [
      {key: 'first_name',     value: firstNameVariable},
      {key: 'last_name',    value: lastNameVariable}
    ].map(x => `${encodeURI(x.key)}=${encodeURI(x.value)}`).join('&');

    return this.http.post(myurl, body, options)
          .retry(NUM_HTTP_RETRIES)
          .map((res: Response) => res.json())
          .toPromise();
  }

}

However, I have an issue when I'm trying to pass in my parameters a base64 image, i.e.

  myPostRequest(){
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded' );
    headers.append('Authorization', 'Bearer '+mytoken);
    headers.append('access_token', ACCESSTOKEN );
    let options = new RequestOptions({ headers: headers });

    let body = [
      {key: 'first_name',     value: firstNameVariable},
      {key: 'last_name',    value: lastNameVariable},
      {key: 'myIdFile',    value: my64baseImgString},
    ].map(x => `${encodeURI(x.key)}=${encodeURI(x.value)}`).join('&');

    return this.http.post(myurl, body, options)
          .retry(NUM_HTTP_RETRIES)
          .map((res: Response) => res.json())
          .toPromise();
  }

In that case the image is reached the server corrupted. I'm not sure since the string is very long if the body variable should be in the form first_name=AName&last_name=LastName&myIdFile=64baseImg.

I have been looking around to find another way to pass the body parameter. I have tried to write it as json object,i.e.

let body = {
  first_name:firstNameVariable,
  last_name:lastNameVariable,
  myIdFile:my64baseImgString
};

or as HttpParams, i.e.

  let body = new HttpParams();
    body.append('first_name',firstNameVariable);
    body.append('last_name',lastNameVariable);
    body.append('myIdFile',my64baseImgString);

I have been looking around and it seems that the body variable needs to be an object, which however in my case doesn't work as expected. I keep having http error if I put it as an object. In Postman if I put the header and the body parameters the way it asks, i.e. with key and a value everything works fine.

What am I doing wrong?

Thanks

Symeon Mattes
  • 817
  • 10
  • 30
  • I have passed it as an object before as per your line `let body = {...}`. What error do you get when you have it like that? – mahi-man Sep 29 '18 at 21:46
  • The server doesn't recognise it. it complains that the parameters first_name etc do not exist. – Symeon Mattes Sep 29 '18 at 21:58
  • They won't be available as parameters, but as the body of the request. If you are using express, check out this post https://stackoverflow.com/q/11625519/4553162 – mahi-man Sep 29 '18 at 23:32

1 Answers1

0

Not sure if the it's the most correct answer, but it worked for me. Actually you can send a json object, i.e.

let body = {
  first_name:firstNameVariable,
  last_name:lastNameVariable,
  myIdFile:my64baseImgString
};

if in your header request you mention that the content is a json object, i.e.

  myPostRequest(){
    var headers = new Headers();
    headers.append('Content-Type', 'application/json' );
    //instead of 
    //headers.append('Content-Type', 'application/x-www-form-urlencoded' );
    headers.append('Authorization', 'Bearer '+mytoken);
    headers.append('access_token', ACCESSTOKEN );
    let options = new RequestOptions({ headers: headers });

    let body = {
      first_name:firstNameVariable,
      last_name:lastNameVariable,
      myIdFile:my64baseImgString
    };

    return this.http.post(myurl, body, options)
          .retry(NUM_HTTP_RETRIES)
          .map((res: Response) => res.json())
          .toPromise();
  }

However the server needs to accept Json objects and allow CORS (Cross-Origin Resource Sharing).

Symeon Mattes
  • 817
  • 10
  • 30