0

I have a login request I am trying to make. I need to make a POST request to the server with some parameters such as username, password, clientId, ect.

Angular 6 code:

let body = new URLSearchParams();
body.set('username', email);
body.set('password', password);
body.set('customerId', environment.customerId);
body.set('grant_type', 'password');

return this.http.post<JWT>(
    this.baseUrl + this.LOGIN_ENDPOINT,
    body.toString(),
    {
      headers: new HttpHeaders({
        'Content-Type': 'text/plain'
      })
    }
)

When I make a POST request, it gets changed to OPTIONS and the browser blocks the response because the Access-Control-Allow-Origin header is not set. However, in the network tab in Inspect Element, the call actually is correct and returns a 200 OK.

I don't have access to change the backend, and the server company is not working with me on it because they can make a request using ajax.

I tried to make the same request, except using jquery and ajax, and it works just fine, the problem seems to be the 'complex request' sent by angular 6.

Ajax code:

$.post("example.com", {
        grant_type: 'password',
        customerId: 'xxx',
        username: 'xxx',
        password: 'xxx'
    });

Ajax code works, Angular code triggers the OPTIONS / Preflight requests

How can I solve this issue?

Chad K
  • 427
  • 3
  • 16
  • 2
    did you do that ajax call from within the browser and within your website? or did you use some CLI or node for that? because it is actually normal that an OPTIONS request will be sent, whenever you do cross origin requests. that's nothing angular does, but the browser itself. – Patrick Kelleter Oct 20 '18 at 05:55
  • I created a simple webpage that made that request from the browser itself. I'm trying to have angular make a simple request that doesn't trigger preflights – Chad K Oct 20 '18 at 05:59
  • Can you show the headers sent by the OPTIONS request? – David Oct 20 '18 at 06:32
  • 3
    As said, preflights are triggered by the browser whenever you are requesting cross origin - not by Angular. Angular literally has nothing to do with that. Preventing preflight requests from happening can only be done by enabling CORS for the given domain on the backend. For further information, see https://stackoverflow.com/questions/29954037/why-is-an-options-request-sent-and-can-i-disable-it – Patrick Kelleter Oct 20 '18 at 07:02

0 Answers0