Azure API 管理 CORS:为什么我得到 "Headers starting with 'Access-Control-' were removed..."

Azure API Management CORS: Why do I get "Headers starting with 'Access-Control-' were removed..."

使用下面的简单策略:

<policies>
    <inbound>
        <cors>
            <allowed-origins>
                <origin>http://microfost.com/</origin>
            </allowed-origins>
            <allowed-methods preflight-result-max-age="300">
                <method>GET</method>
                <method>POST</method>
                <method>PATCH</method>
                <method>DELETE</method>
            </allowed-methods>
            <allowed-headers>
                <header>content-type</header>
                <header>accept</header>
                <header>Authorization</header>
            </allowed-headers>
        </cors>
    </inbound>
</policies>  

HTTP 请求

OPTIONS https://XXXX.azure-api.net/demo/XXX/XXX/* HTTP/1.1
Host: XXXX.azure-api.net
Ocp-Apim-Trace: true
Ocp-Apim-Subscription-Key: <secret>
Origin: http://microfost.com
Access-Control-Request-Headers: Authorization
Access-Control-Request-Method: GET

回复内容

Access-Control-Allow-Origin: http://microfost.com
Ocp-Apim-Trace-Location: <trace>
Date: Mon, 27 Feb 2017 20:09:14 GMT
Content-Length: 0

我收到此消息并期待 Origin 响应 header 我在 3 API 秒中有 2 次没有收到任何消息(1 API 正在使用与预期相同的策略) .

**Inbound**
[...]
cors (0 ms)
"Cross domain request was well formed and was allowed to proceed. CORS related headers were added to the response."

**Backend**

No records.
Outbound

cors (0 ms)
{
    "message": "Headers starting with 'Access-Control-' were removed from the response. ",
    "headers": []
}
transfer-response (0 ms)
{
    "message": "Response headers have been sent to the caller."
}

在我看来,这是一种无意义的行为,可能是一个错误。在提交之前我想问你有没有解释?为什么我会得到这个?

Headers starting with 'Access-Control-' were removed from the response.

有两种方法可以在 Azure API 管理中执行 CORS。自动 - 只需在所需范围内删除和配置 CORS 策略,APIM 将负责响应与现有操作匹配的 OPTIONS 请求。

或者您可以选择手动方式 - 创建一个单独的操作来响应 OPTIONS 方法并在策略中手动形成响应,可能使用 return-response 策略。

你遇到的问题是因为你两者都有。他们基本上是冲突的。 CORS 策略将请求识别为交叉源并在请求完成后安排处理,但是 return-OPTIONS 操作级别的响应策略会在 CORS 策略可以采取行动之前立即中断此处理管道和 returns 响应。

由于您使用的是 CORS 策略,因此您应该从 API 中删除 OPTIONS 操作以使事情正常进行。

在您的标签中添加属性 allow-credentials="true"

参见: https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/api-management/api-management-cross-domain-policies.md

我遇到了类似的问题。添加 <base /> 为我修复了它。

<policies>
    <inbound>
        <base />
        <!-- your policy here -->
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>