javascriptajaxgoogle-chromerequest-cancelling

CORS ajax call fails despite of the appropriate Access-Control-Allow-* headers


I am performing an ajax call from a third-party-hosted script to my endpoint.

The preflight call looks like this in Chrome:

GENERAL
Request URL: https://my_endpoints_url
Request Method: OPTIONS
Status Code: 200 
Remote Address: 21.188.37.117:443
Referrer Policy: origin-when-cross-origin

RESPONSE HEADERS
access-control-allow-headers: *
access-control-allow-methods: *
access-control-allow-origin: *
allow: OPTIONS, TRACE, GET, HEAD, POST
content-length: 0
date: Thu, 14 Jan 2021 15:45:17 GMT
public: OPTIONS, TRACE, GET, HEAD, POST
server: Microsoft-IIS/10.0
strict-transport-security: max-age=31536000
x-powered-by: ASP.NET

REQUEST HEADERS
:authority: my_endpoints_host
:method: OPTIONS
:path: my_endpoints_path
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: fr,en-US;q=0.9,en;q=0.8,ca;q=0.7,es;q=0.6,pt;q=0.5
access-control-request-headers: authorization,content-type
access-control-request-method: POST
origin: https://c.cs160.visual.force.com
referer: https://c.cs160.visual.force.com/
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36

I configured my endpoint's server to allow every header, method, and origin, as visible in the response headers. Despite of this, Chrome keeps canceling the subsequent POST request.

What am I missing?

Edit: If I remove the access-control-allow-headers from the server response, Chrome writes a proper error message in the console "Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response." And the POST request is tagged as (failed) in the network tab. When adding access-control-allow-headers : " * ", there is no error message, and the POST request is tagged as (canceled)

Thank you


Solution

  • The solution was not related to CORS at all, but the website (SalesForce) hosting my JS script.

    Indeed SalesForce reloads the page after every ajax call. Chrome detects that the DOM node that triggered the ajax call is gone, so it judiciously cancels the request.

    My solution was to make my ajax call synchronous.

    Thanks @Quentin and @sideshowbarker for the ideas