Ionic - Send localhost post to external PHP API

Asked

Viewed 333 times

2

Hello!

I’m developing an app with Cordova/Ionic and I’m trying to send data via post as follows:

public async login(usuario: string, senha: string): Promise<any[]>{
    let body = new FormData();
    body.append('usuario', usuario);
    body.append('senha', senha);

    let response: any = await this.http
        .post(this.api.url + '?model=usuario&function=login', body, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
                'Token': this.api.token
            }
        })
        .toPromise()
        .catch(error => console.log(error));

    console.dir(response);

    if(response == null){
        response = [];
    }

    return response;
}

I happen to be on the localhost and the api on an external php site. I’ve been able to request via get, but the post doesn’t work, the api doesn’t receive any data.

To get around cross origin problems I made a definition of proxys in the file Ionic.config.json.

When I run the POST function, I can see four requests being sent using Chrome debug:


Request URL: http://localhost:8100/api? model=usuario&function=login Request Method: GET Status Code: 301 Moved Permanently


Request URL: http://localhost:8100/api? model=usuario&function=login Request Method: POST Status Code: 301 Moved Permanently


Request URL: https://www.sitedaapi.com.br/app/api/? model=usuario&function=login Request Method: OPTIONS Status Code: 200 OK


Request URL: https://www.sitedaapi.com.br/app/api/? model=usuario&function=login Request Method: GET Status Code: 200 OK

...

It seems that where it would be to send a POST ends up sending a GET.

1 answer

1

I already solved the problem. There were two things:

1 - In the file Ionic.config.json I put the wrong proxyUrl address, was missing 'www' (for some reason making GET requests worked even without 'www')

2 - I removed the 'Content-Type' from the 'Header' of the request and was able to receive the data sent via post in the array format in PHP.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.