Search code examples
headercorsfetchresponserequestly

How to modify response headers without using a third party app


I want to make a simple fetch request to siteA from siteB, but I am blocked by CORS policy.

fetch(siteA, {
  credentials: "include",
  headers: {
            'Access-Control-Allow-Origin': siteB,
            'Access-Control-Allow-Credentials': 'true'`}
})

error:

Access to fetch at siteA from origin siteB has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

However, I was able to get this fetch call to work if I use a chrome extension called Requestly, which allows me to change Response headers so that

'Access-Control-Allow-Origin': siteB,
'Access-Control-Allow-Credentials': 'true'

I am wondering if it is possible to apply the same change to the response headers like how Requestly did it, without using Requestly or any other third-party extension/app.

thank you


Solution

  • What you're trying to do is exactly what CORS prevents.

    In simple words, Browsers won't allow any response from siteB's server on siteA unless siteB's server gives permission for it. This permission is given as response headers on preflight request.

    As you said, you can either rely on browser extensions like Requestly to manipulate CORS headers or use a third-party hosted service like CORS-Anywhere that does reverse proxy the request.

    PS - CORS-Anywhere hosted service is strict to be used only for development reasons or you can take the GitHub code and deploy it on your servers. Refer this SO Post on how to use CORS Anywhere.