Home > Back-end >  Cross-domain POST doesn't work with Angular HttpClient but works with jQuery
Cross-domain POST doesn't work with Angular HttpClient but works with jQuery

Time:04-25

I am migrating to Angular 13 and I want to use HttpClient instead of jQuery.ajax.

The following jquery code works:

function asyncAjax(url: any){
  return new Promise(function(resolve, reject) {
          $.ajax({
            type: 'POST',
            crossDomain: true,
            xhrFields: {
              withCredentials: true
            },
            url: url,
            data: null,
            contentType: "text/plain; charset=utf-8",
            dataType: "json",
            success: function(data) {
              resolve(data) // Resolve promise and when success
            },
            error: function(err) {
                reject(err) // Reject the promise and go to catch()
            }
          });
  });
}
...
const json: any = await asyncAjax(url);

However, when I do with HttpClient:

private readonly _httpClient: HttpClient;

constructor(httpClient: HttpClient) {
  this._httpClient = httpClient;
}

...
const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});
const json = await firstValueFrom(this._httpClient.post<T[]>(url, null, 
    { headers: headers, withCredentials: true}));

I get:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [url]. (Reason: CORS request external redirect not allowed).

Could anyone say how to make it work with HttpClient?

CodePudding user response:

In your jQuery code you are sending no data at all and claiming you are sending plain text.

data: null,
contentType: "text/plain; charset=utf-8",

In your Angular code you still aren't sending any data, but this time you are claiming you are sending JSON.

const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});

JSON isn't a data type supported by HTML forms which means to send it on a cross-origin request the browser will send a preflight request.

The server isn't granting permission using CORS in its response to that preflight request and seems to be issuing a redirect instead.


The quick and dirty solution here is to send the same Content-Type header as you were when the code worked.

The better solution is to consider your API design. Why are you using a POST request but not POSTing any data in the first place? Possibly this should be a GET or DELETE request instead.


It is also possible that the cause of the redirect is that the value of url has changed (maybe from http://example.com/foo/ to http://example.com/foo) and that needs to be corrected.

  • Related