Cors error being thrown from APIM developer portal for return-response policy

Sanchita Sengupta 6 Reputation points
2021-06-06T09:24:59.353+00:00

I am trying to run my APIM API from.developer portal. I have added the full CORS policy as below:

<cors>
<allowed-origins>
<origin></origin>
</allowed-origins>
<allowed-methods>
<method>GET</method>
<method>POST</method>
<method>PUT</method>
<method>DELETE</method>
<method>HEAD</method>
<method>OPTIONS</method>
<method>PATCH</method>
<method>TRACE</method>
</allowed-methods>
<allowed-headers>
<header>
</header>
</allowed-headers>
<expose-headers>
<header>*</header>
</expose-headers>
</cors>

It works fine until i add return-response policy within on-error - then it again starts throwing the cors policy error- asking to enable cors on browser, even though cors already is enabled. Is there any other cors tag to add?

My on-error code:
<on-error>
<choose>
<when condition="@(context.Response.StatusCode != 200)">
<return-response>
<set-status code="@(context.Response.StatusCode)" reason="@(context.LastError.Reason)" />
<set-body>
new JProperty("Error Reason", context.LastError.Reason)
).ToString();
}</set-body>
</return-response>
</when>
<otherwise />
</choose>
<base />
</on-error>

I have checked after changing origin * to origin as link of the dev portal - I get the same error

The policy works on postman.

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
2,117 questions
{count} vote

2 answers

Sort by: Most helpful
  1. ChaitanyaNaykodi-MSFT 26,101 Reputation points Microsoft Employee
    2021-06-08T00:35:42.067+00:00

    Hello @Sanchita Sengupta , Welcome to Microsoft Q&A! Thanks for posting the question.

    Can you please confirm if you have the cors policy applied at Global API level or at product level? I ask because based on the information here if you apply the CORS policy in the Product scope, instead of the API(s) scope, and your API uses subscription key authentication through a header, your console won't work. The browser automatically issues an OPTIONS HTTP request, which doesn't contain a header with the subscription key. Because of the missing subscription key, API Management can't associate the OPTIONS call with a Product, so it can't apply the CORS policy. As a workaround you can pass the subscription key in a query parameter.
    Please let me know if there are any concerns. Thank you!

    0 comments No comments

  2. Xu Zhenghao 0 Reputation points
    2023-04-25T08:49:38.8366667+00:00

    In on-error section, do not use <return-response>. Then this problem will not happen.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.