Azure API Management > CORS and POST
Asked Answered
T

1

13

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?

Tauto answered 30/9, 2014 at 13:15 Comment(5)
To answer my own question, the allowed-headers contained a bad value. In javascript, I do set 'contentType', but the name of the header for which the OPTIONS is fired, is called 'content-type'. Off to the next hurdle.Tauto
Thanks for answering your own question as i ran into the same thing. javascript was contentType and like you I applied (and corrected) the <allowed-headers>. THANKS!Quickie
I believe there was a recent change. I suddenly was dealing with OPTIONS for a POST were that wasn't the case before. I had to set * for headers in Azure API Management. Not sure what changed but it wasn't my code :( Anyway, it's resolved now, just wasted a whole day!Quickie
@FrederikVellemans - worth posting your own answer as an answer so it doesn't sit unanswered. (uh. That hurt my head)Eld
btw you don't need to enable OPTIONS method its a standard for CORS and is handled automaticallyAmbulacrum
N
2

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

Nordstrom answered 30/9, 2014 at 13:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.