HTTP Post Request

This give a TS error, as this {'cardToken='+token+'&amount=500'} is not an object.

Then make it { "cardToken": token, "amount": 500 }

1 Like

Still give the same error: here’s my latest code:


  var data = {
        "cardToken": token,
        "amount": 500
      };

      var header = { "headers": {"Content-Type": "application/json"} };

      this.http.post('some.domain', data, header).then(data => {
        console.log(data.status);
      }).catch(error => {
        console.log(error.status);
      });

ERROR:

 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryM length]: unrecognized selector sent to instance

Not

Change to headers. I mean no ".

Tried it, still throws that same error…

      var data = {
        'cardToken': token,
        'amount': 500
      };
      var header = { headers: {'Content-Type': 'application/json'} };

Try

import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
.....

let headers = new Headers(
{
  'Content-Type' : 'application/json'
});
let options = new RequestOptions({ headers: headers });

let data = JSON.stringify({
  cardToken: token,
  amount: 500
});

return new Promise((resolve, reject) => {
  this.http.post('url', data, options)
  .toPromise()
  .then((response) =>
  {
    console.log('API Response : ', response.json());
    resolve(response.json());
  })
  .catch((error) =>
  {
    console.error('API Error : ', error.status);
    console.error('API Error : ', JSON.stringify(error));
    reject(error.json());
  });
});

This code from my projects.

6 Likes

@dimitri320 check out my repo here: https://github.com/danielsogl/benchmark-app-ionic

the provider method

  post(item: any) {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.endpoint + '/posts', item, options)
      .map(res => res.json())
      .toPromise();
  }

the object

      const object = {
        "userId": i,
        "id": i,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
      }
2 Likes

Thanks a lot, this works well! Btw, can u advice what’s the difference between these?

import { HTTP } from '@ionic-native/http';
import { Http, Headers, RequestOptions } from '@angular/http';
2 Likes

Ignore the import { HTTP } from '@ionic-native/http'; import.

1 Like

I’m not sure about different. But @rapropos told me in this topic “If you talk to a backend REST interface”, you don’t want the ionic-native HTTP, you want Angular’s Http".

1 Like

You don’t want to use THIS native plugin :wink: But native HTTP calls are always faster.

1 Like

OH MY GOD YOU ARE A LEGEND. Have been trying to figure out my issue for a while now with the headers and now its finally working.

1 Like

Hi @ThunderBirdsX3
I know this post is old, but I am still stuck on this problem.
When i use “import { Http, Headers, RequestOptions } from ‘@angular/http’;”, I perpetually run into “Response with status: 0 for URL: null” errors.
But at least with “import { HTTP } from ‘@ionic-native/http’;”, I can talk to the php file on my server, only that “$_POST[‘jsonRequest’]” on the php end never sees the json data sent.

Can you offer any advice, or do you need to see my code?

Hi
I finally solved my problem. I did not configure the php file on the server properly to receive the json.
So as it stands, I will continue to use “import { HTTP } from ‘@ionic-native/http’;” as that is what works for me.
I am using ionic3 by the way.

please solve this
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://stage.noargs.com/appi. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

My Code is this…

import { Component } from ‘@angular/core’;
import { NavController } from ‘ionic-angular’;
import { Injectable } from ‘@angular/core’;

import { HttpClient, HttpHeaders } from ‘@angular/common/http’;
//import { Headers } from ‘@angular/http’;

//import ‘rxjs/add/operator/map’;

@Component({
selector: ‘page-home’,
templateUrl: ‘home.html’
})

@Injectable()
export class HomePage {
users = {};
constructor(public navCtrl: NavController, public http: HttpClient) {

}

submitUser() {

console.log(this.users);

let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
//let options = new RequestOptions({ headers: headers });


let data=JSON.stringify({name:"raja",email:"rj@gmail.com", phone:"7896325410", address:"New Ashoknagar" });
this.http.post("https://stage.noargs.com/appi/users",data, { headers: headers })

// .map(res => res.json(data))
.subscribe(res => {
alert("success "+res);
}, (err) => {
alert(“failed”);
});
}

}

Simple: Add the header to the response (!) of the server or find another way to communicate with that API (Ionic Native HTTP for example).

Hy all, actually I am getting ’ post ’ of undefined error. see below:
Screenshot_17
And here is my code:


Please help.

In my project I solved in this way:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html'
})
export class HomePage implements OnInit {

  constructor(private http: HttpClient) { 

    let data = JSON.stringify({
      key: 'val',
      key2: ' otherVal'
    });

    this.http.post('http://www.myRoot.it/api/myApp.php', data).subscribe((response) => {
      console.log(response);
    });
  }


}

On the server the Access-Control-Allow-Origin header must be set

1 Like

Thanks for replying, I was solved it with another way!