Ionic 2 - How to make a login post request?

為{幸葍}努か 提交于 2020-04-16 03:33:48

问题


I need to implement login in my Ionic 2 app. For now I just need to be sure that the email and the password are properly received and get back a basic response.

I have successfully tested a GET request to the API and it is properly working, but I am not able to get the POST request working.

I have tried two approaches:

  1. Using subscribe:

    Login component:

    submitLogin() 
    {
        var email = this.loginForm.value.email.trim();
        var password = this.loginForm.value.password.trim();
    
        this.userService.makeLogin(email, password);    
    }
    

    Service:

    makeLogin(email: string, password: string) 
    {
        var body = JSON.stringify({
            email: email,
            password: password
        });
    
        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    
        this.http
            .post(this.loginUrl, body, { headers: headers })
            .subscribe(data => {
                        console.log('login API success');
                        console.log(data);
                    }, error => {
                        console.log(JSON.stringify(error.json()));
            });
    }
    

    The API (codeIgniter): (code at minimum for testing purpose)

    public function testLoginIonic2()
    {
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
    
        $account_email  = $this->input->post('email');
        $account_password   = $this->input->post('password');
    
        echo json_encode($account_email);
    }
    

    RESULT:

    The connection to the server seems okay - but no data is returned - the body of the response is empty

  2. Using a Promise:

    Login component:

    submitLogin() 
    {
        var email = this.loginForm.value.email.trim();
        var password = this.loginForm.value.password.trim();
    
        this.userService.testLogin(email, password)
                .then(data => {
                    console.log('response data');
                    console.log(data);
                }); 
    }
    

    Service:

    testLogin(email: string, password: string): Promise<any> 
    {
        var body = JSON.stringify({
            email: email,
            password: password
        });
    
        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    
        return this.http
            .post(this.loginUrl, body, {headers: headers})
            .toPromise()
            .then(res => res.json().data);
    }
    

    API: Same as before

    RESULT:

    I get this error message: Unexpected end of JSON input (probably because the response is empty and thus not in JSON format).

Why do I get an empty response?

The form is properly working. The error is not there.

So there must be something wrong in the request, but what?

EDIT:

Testing with Postman it seems that the parameters are empty. Probably they are not properly sent.


回答1:


Thanks for the replies.

The answer from @hgoebl is properly working.

I found a solution that is a bit more simple using URLSearchParams:

Component:

submitLogin() 
{
    var email = this.loginForm.value.email.trim();
    var password = this.loginForm.value.password.trim();

    this.userService.makeLogin(email, password)
        .subscribe((response) => {
            console.log(response);
        }, (error) => {
            console.log(error);
        });
}

Service:

makeLogin(email: string, password: string) 
{       
    let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('email', email);
    urlSearchParams.append('password', password);
    let body = urlSearchParams.toString()

    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

    return this.http
        .post(this.loginUrl, body, { headers: headers })
        .map(response => response.json())
}

Keep in mind that URLSearchParams has to be imported in the service:

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

EDIT:

I moved the subscribe inside the component to be able to handle the response data inside the component.




回答2:


For me it looks like if the problem starts by sending in the wrong format. You're telling the server it's content is application/x-www-form-urlencoded, but you're sending JSON.

You might try this:

testLogin(email: string, password: string): Promise<any> 
{
    var headers = new Headers();
    headers.append('Content-Type',
        'application/x-www-form-urlencoded; charset=UTF-8');

    let params = {email, password};
    let body = this.toFormUrlEncoded(params);

    //... your post request
}

private toFormUrlEncoded(object: Object): string {
    return Object.keys(object)
        .map(key => {
            return encodeURIComponent(key) + '=' + 
                   encodeURIComponent(object[key]);
        })
    .join('&');
}

As an alternative you could also change your content-type to JSON and change your server to decode JSON.




回答3:


Shouldn't you do map after http.post?

this.http
    .post(this.loginUrl, body, { headers: headers })
    .map(response => response.json())
    .subscribe(data => {
        console.log('login API success');
        console.log(data);
    }, e => {
         console.log(e);
    });

Your response from the observables looks ok, but not parsed.



来源:https://stackoverflow.com/questions/40723010/ionic-2-how-to-make-a-login-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!