How can I make an HTTP POST request to my server?

#1

Hey there! I have implemented back-end for Ionic. Until then I tested my api using cURL from my Linux terminal. I used this command: curl --data "some=parameter&another=parameter&and=another&one=parameter" https://myserver/api/my/endpoint. So, how can I do that the same thing using Ionic? :slight_smile:

Also, please apologize my english. I’m not native.

#2

You should use a provider for this. You can read more info here:
https://angular.io/tutorial/toh-pt4
This is a simple example of a http post for ionic:

import { Http, Response } from '@angular/http';

export class Api {

    constructor(public http: Http) {}

    post(apiUrl: string, data: any = {}) {
        return this.http.post(apiUrl, JSON.stringify(data))
            .map((response: Response) => {
                return response.json();
            });
    }
}
#3

I tried this, but it doesn’t work. Why? :frowning:

let postParams = {some:'some', another:'some'};

this.http.post("https://myserver/api/my/endpoint", JSON.stringify(postParams)).map((response: Response) => {
    console.log('test');
});
#4

Check for errors you can use chrome dev tools to debug check the network tab.
You can also add in your code some error handling eg.

this.http.post("https://myserver/api/my/endpoint", JSON.stringify(postParams)).map((response: Response) => {
    console.log('test');
})
.catch((error: Response) => {
 // handle errors here console.error(error)
});
1 Like
#5

Still nothing. My server responding, which is good, but…

My code:

this.http.post("http://myserver/api/my/endpoint", JSON.stringify(postParams)).subscribe(response => {
    return console.log(JSON.stringify(response));
});

And i’m getting this error:

ERROR Object { _body: "{"responseHttpCode":"400"}", status: 400, ok: false, statusText: "Bad Request", headers: Object, type: 2, url: "http://myserver/api/my/endpoint" }

My server responded with 400 HTTP error. That means, that my api can’t parse my POST fields (I didn’t send them):

some=parameter&another=parameter&and=another&one=parameter

How to fix this?

#6

What’s your backend stack ?
Did you check the request headers url etc in chrome network tab is everything ok ?
Can you try again setting the headers

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

this.http.post("https://myserver/api/my/endpoint", JSON.stringify(postParams), new RequestOptions({ headers: headers })).map((response: Response) => {
    console.log('test');
})
.catch((error: Response) => {
 // handle errors here console.error(error)
});

Don’t forget to import Headers, RequestOptions first

#7

That’s not JSON. Use URLSearchParams. Incidentally, there is no need to manually stringify post bodies or set content type. Angular does that.

#8

Can you provide example? I have no idea how this works. :confused:

#9

So… I Googled and found this (works ok):

this.http.post("https://httpbin.org/post", "firstname=Nic")
        .subscribe(data => {
            var alert = Alert.create({
                title: "Data String",
                subTitle: data.json().data,
                buttons: ["close"]
            });
            this.nav.present(alert);
        }, error => {
            console.log(JSON.stringify(error.json()));
        });

Edited to my needs:

this.http.post("https://myserver/api/my/endpoint", "some=parameter&another=parameter&and=another&one=parameter").subscribe(data => {
    console.log(JSON.stringify(data.json()));
}, error => {
    console.log(JSON.stringify(error.json()));
});

…and my server responded but with error. The problem is my params (some=parameter&another=parameter&and=another&one=parameter"). With one parameter it works ok, but with more than one, it’s useless. :confused:

#10

If you want to pass the params with this format you should use URLSearchParams as @rapropos
suggested.
An example for your case:
let params = new URLSearchParams()
params.append(‘some’, parameter); … etc

Don’t forget to import URLSearchParams

#11

Thanks guys. URLSearchParams works well. :slight_smile:

#12

not work for me unable to send parameter response is wrong plz give me code.

1 Like