Azure API Management > CORS and POST

2020-07-05 06:12发布

问题:

I'm using Azure API Management to deliver a clean interface to third parties for integration purposes.

I want do a POST with a JSON object to create this object in the backend. This works fine in the test console available in the portal site, but it doesn't work when I try to do a simple client script from a web page:

$.ajax({
    url: 'https://.azure-api.net/api/samplerequest/create?' + $.param(params),
    type: 'POST',
    data: JSON.stringify(sampleRequest),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data, par2, par3) {
        $("#txtResult").val(JSON.stringify(data));
    }
});

Setting the contentType header to 'application/json' forces the browser to perform an OPTIONS call first. My WebAPI project is setup to enable CORS and I have tested this. My WebAPI project returns the following headers for the OPTIONS method:

Access-Control-Allow-Head... content-type Access-Control-Allow-Orig... *

However, if I try to call this operation by using the Azure Management API, I get a 200 status for the OPTIONS method, but no other headers are present. I've tried many policy-configurations, this was my latest attempt:

<policies>
    <inbound>
        <base />
        <cors>
            <allowed-origins>
                <origin>*</origin>
                <!-- allow any -->
            </allowed-origins>
            <allowed-methods>
                <method>POST</method>
                <method>OPTIONS</method>
            </allowed-methods>
            <allowed-headers>
                <header>contentType</header>
            </allowed-headers>
        </cors>
    </inbound>
    <outbound>
        <base />
    </outbound>
</policies>

What am I missing to make this work?

回答1:

The header in the ajax request should be 'content-type' rather than 'contentType'