MAK2020
MAK2020

Reputation: 93

Chrome cancels Angular 2 request

I am writing an Angular 2 app that calls to a PHP api on localhost. The HTML in login.component.html is as follows:

<form name="loginForm" class="loginForm">

    <input type="text" name="email" id="email" placeholder="Email" [(ngModel)]="model.email" size="65">

    <input type="password" name="password" id="password" placeholder="Password" [(ngModel)]="model.password" class="input" size="20">

    <button tabindex="12" class="btn-full submit" (click)="attemptLogin()">Log In</button>
</form>

Then login.component.ts has the attemptLogin() function:

attemptLogin(){
    this.identityService.attemptLogin(this.model).subscribe(
        result => {
            if(result.isauthenticated){
                console.log('Successful Auth');
            }else {
                console.log('Failed Auth');
            }
        }, 
        err => {
            console.log(err);
        });  
}

And then in identityService.ts I have:

attemptLogin(credentials: Credentials): Observable<Authorization> {

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

    let bodyString = JSON.stringify(credentials); 


    return this.http.post('http://localhost:8000/login', bodyString, options)
        .map((res:Response) => res.json())
        .catch((error:any) => Observable.throw(error.json().error || 'Server error'))
}

I made sure the backend php is working and returning a valid response. My issue is that chrome cancels the request, IE the same, but firefox does work and successfully returns the response. This worked at some point, I updated chrome recently, which might have something to do with it. I also made sure this is not a CORS issue, since it really worked in chrome before the update, and also works fine with Mozilla. Here is the Chrome response:

enter image description here

And finally the cancelled request header: enter image description here

thoughts?

Upvotes: 1

Views: 2271

Answers (1)

Steve G
Steve G

Reputation: 13417

My initial guess is that you need to add the type="button" attribute/value to your button tag. The default behavior of a button tag in Chrome is to submit the form, which is cancelling your request (when the browser posts the form back to itself).

For example:

<!-- Added button 'type' attribute/value -->
<button type="button" tabindex="12"...

MDN Documentation

Quoted from W3Schools:

Tip: Always specify the type attribute for a <button> element. Different browsers use different default types for the <button> element.

Upvotes: 5

Related Questions