Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
POST de dominio cruzado no funciona con Angular HttpClient pero funciona con jQuery

Estoy migrando a Angular 13 y quiero usar HttpClient en lugar de jQuery.ajax.

El siguiente código jquery funciona:

 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);

Sin embargo, cuando lo hago con 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}));

Yo obtengo:

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

¿Alguien podría decir cómo hacer que funcione con HttpClient?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

En su código jQuery, no está enviando ningún dato y afirma que está enviando texto sin formato .

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

En su código Angular todavía no está enviando ningún dato, pero esta vez afirma que está enviando JSON .

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

JSON no es un tipo de datos compatible con formularios HTML, lo que significa que para enviarlo en una solicitud de origen cruzado, el navegador enviará una solicitud de verificación previa.

El servidor no está otorgando permiso usando CORS en su respuesta a esa solicitud de verificación previa y parece estar emitiendo una redirección en su lugar.


La solución rápida y sucia aquí es enviar el mismo encabezado Content-Type que estaba cuando el código funcionó.

La mejor solución es considerar el diseño de su API. ¿Por qué está utilizando una solicitud POST pero no está enviando ningún dato en primer lugar? Posiblemente, esto debería ser una solicitud GET o DELETE en su lugar.


También es posible que la causa de la redirección sea que el valor de la url haya cambiado (tal vez de http://example.com/foo/ a http://example.com/foo ) y eso debe corregirse.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!