Tuesday, March 15, 2022

[FIXED] Http calls are immediately cancelled

Issue

I have an angular 4 front end with a CakePHP 3 backend. When I make a request to an API end point using my browser or Rest Client I receive a response. But when I send the response from the angular service it immediately shows cancelled in the network.

At first I assumed it was a CORS issue. I have tried both with and without CORS enabled. I also added $this->Security->csrfCheck = false; to my AppController.php which led me to believe that the local server is never hit (no breakpoints were firing).

So instead I am looking at Angular side of the equation. I have attempted to set my headers but that also does not work.

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

login(loginData) {
    const headers = new Headers({'Content-Type': 'application/json'});

    const url:string = this.backendUrl + '/auth/login/?';

    return this.Http.post(
        url,
        JSON.stringify(loginData),
        { headers: headers }
    ).map(
        res => res.json
    ).map(
        response => function(response) {
            ...
        },
        error => function(error) {
            ...
        }
    );
}

I am in the process of migrating from 1 to 4. So I know that it worked in Angular 1 using $http requests.

function login(loginData) {
   var = this.backendUrl + '/auth/login/?';

   $http.post(url, loginData).then( ... );
}

Here is my component which uses the subscription:

login = function(activeUser):ActiveUser|boolean {
    this.isLoggingIn = true;

    return this.LoginService.login(activeUser).subscribe(
        activeUser => function(activeUser) {
            if (activeUser) {
                this.activeUser = activeUser;
            } else {
                this.reset();
            }

            return activeUser;
        }.bind(this)
    ).complete(
        function() {
            this.isLoggingIn = false;
        }.bind(this)
    );
};

Solution

The problem had to do with how Angular $http now handles CORS requests. In the updated version there are two requests sent, an OPTIONS request and then the actual GET/POST request. So I had to change my backend to return a 200 on the OPTIONS without executing the command and instead execute on the second request.



Answered By - Jeremy

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.