Allow CORS requests Azure Function hosted in Kubernetes

2/27/2019

There's plenty of help with configuring CORS when running an Azure Functions app in local dev or inside Azure on the web.

But we're currently hosting the functions in our own Kubernetes cluster, and I've tried setting an environment variable 'Host' to '{"CORS":"*"}', which is what it looks like Azure does, but this doesn't seem to have added the CORS headers.

Is this because it ignores the environment variable if its not hosted locally or in Azure? In which case, do I need to be running in production with func so I can pass the allowed origins parameters to the commandline app? (The Dockerfile MS give you uses dotnet with the WebHost.dll - and I'm not sure where to find options for that command).

-- Ian Grainger
azure
azure-functions
cors
kubernetes

1 Answer

2/28/2019

I've made a similar for response for Raspberry Pi in another SO post which is applicable here too. Here is the same answer for reference

CORS is basically just sending the appropriate headers in your response.

On Azure, this is taken care of by the platform itself but since you will be running/accessing the functions runtime directly from a container, you can just set them on the response object.

For example, if you are using NodeJS/JavaScript for your functions, set the headers using context.res

context.res = {
  status: 200,
  headers: {
    'Access-Control-Allow-Credentials': 'true',
    'Access-Control-Allow-Origin': '*', // Or the origins you want to allow requests from
    'Content-Type': 'application/json'
  },
  body: {
    just: 'some data'
  }
};

Also, another way to do CORS is using a reverse proxy that adds the headers for you, especially makes things easier if they are the same for all your functions.

-- PramodValavala-MSFT
Source: StackOverflow