CORS and LWC Client calls

calloutdeveloperjavascriptlightning-web-components

I built a LWC that calls out to our ALM so a user can submit a ticket directly in SF.
However, I'm running into some CORS issues – within fetch() if I don't pass mode: no-cors then I receive:

has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Of course, removing CORS does not allow me to pass in the authorization header nor content-type which malforms my request.

Am I correct that this is due to the client-side nature of fetch(), that if I were to make the callout via Apex then I would be server side and wouldn't have to contend with origin headers?

I have this same functionality working through our bespoke RoR app so assumed it had to do with client-side behavior.

Thanks for your response, relatively new to LWC and this is the first callout I've done with them – typically build in Apex, but wanted to mix things up a bit.

Best Answer

The issue resided on the endpoint, the CORS protection was on the service being called.

Vendor confirmed they have strict CORS protection and the call needs to be sent server, not client side.

If the vendor did not have strict CORS protection, the JS fetch method will work. Confirmed with another endpoint.

Related Topic