Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

220
Visualizações
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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda