Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

186
Vistas
Cross-domain POST doesn't work with Angular HttpClient but works with jQuery

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda