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?
Previously, you had to manage most of this via XML copy and paste, but now there is an easy configuration wizard to follow. Inside Azure API Manager, select your API, All Operations, then go ahead and select “Add Policy” on Inbound processing. On the next screen, find the option to “Allow cross-origin resource sharing (CORS)” as shown below
Inside Azure API Manager, select your API, All Operations, then go ahead and select “Add Policy” on Inbound processing. On the next screen, find the option to “Allow cross-origin resource sharing (CORS)” as shown below By default, the options presented to you will only be to select the “Allowed origins”, which is defaulted to *.
In most cases GET requests are allowed however requests of type POST, PUT or DELETE would be denied to minimise potential malicious behaviour. That is exactly what was happening in my case, trying to consume the API I was hosting on the APIM (Microsoft Azure) from client-side (POST AJAX request).
The cors policy adds cross-origin resource sharing (CORS) support to an operation or an API to allow cross-domain calls from browser-based clients. If request matches an operation with an OPTIONS method defined in the API, pre-flight request processing logic associated with CORS policies will not be executed.
The header in the ajax request should be 'content-type' rather than 'contentType'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With