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