HTTP Post Request


#1

I’m trying to run the following code and I’m getting this error, my code is below. Any advice how to fix this will be highly appreciated! Thanks so much!

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

      this.http.post('https://some.domain', ('cardToken='+token+'&amount=500'), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(data => {
        console.log(data.data);
      }).catch(error => {
        console.log(error.status);
      });

#2

Why your code was POST with GET parameters?

You should.

this.http.post('https://some.domain', 
{ 
  cardToken : token,
  amount, 500
}, 
{
  headers: { 'Content-Type': 'application/json' }
})
.then(data => {
  console.log(data.data);
}).catch(error => {
  console.log(error.status);
});

Try to find more information from THIS.


#3

It seems like you’re passing wrong arguments. According the Angular $http docs, data variable must be a JS object.

Try the following code:

this.http.post('https://some.domain', {'cardToken='+token+'&amount=500'}, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(data => {
        console.log(data.data);
      }).catch(error => {
        console.log(error.status);
      });

#4

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


#5

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


#6

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

#7

Not

Change to headers. I mean no ".


#8

Tried it, still throws that same error…

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

#9

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.


#10

@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"
      }

#11

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';

#12

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


#13

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".


#14

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


#15

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.


#16

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?


#17

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.


#18

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).


#19

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”);
});
}

}


#20

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