Search code examples
javascriptjqueryazureazure-cognitive-search

Unable to query Azure Search using jquery POST


I set the CORS to "All" for the Azure Search Index I'm trying to query, and also added "*" to the blob storage that the index is hitting. I've tried a variety of query params / options, but still run into the "No 'Access-Control-Allow-Origin' header" error. I'm running from Eclipse, a tomcat server, java web app, which calls the javascript function. I'm passing the api-key for the Search service and setting the headers; where is this going wrong? I also tried deploying the web app to a VM in Azure in the same datacenter and same resource group, and still get the same error. I've tried adding the beforeSend function as well to the ajax call, didnt help.

var index = "https://<my-azure-storage>-azuresearch.search.windows.net/indexes/<my-search-index>/docs?";
var params = encodeURIComponent("api-version=2016-09-01&search=hematology");
var theUrl = index + params;
$.ajax({
    method: "POST",
    url: theUrl,
    headers: {'api-key': "<azure-search-main-admin-key>",
        "Access-Control-Allow-Origin": "*"},
    contentType: "application/json",
    success: function(data) {
        alert("Search Result" + data);
    },
    error: function(jqxhr, textStatus, e) {
        alert("Error (jqxhr): " + jqxhr.responseText);
        alert("Error Status: " + textStatus);
        alert("Error (e): " + e);
    }
});

Error in browser: XMLHttpRequest cannot load https://..url../docs?api-version%3D2016-09-01%26search%3Dhematology. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 400.


Solution

  • To fix this issue, you could try this way:

    1. As Bruce Johnston Said, change the verb to GET.
    2. Use function encodeURI instead of encodeURIComponent to encode the query string.

    And the code look like:

    var index = "https://<my-azure-storage>-azuresearch.search.windows.net/indexes/<my-search-index>/docs?";
    var params = encodeURI("api-version=2016-09-01&search=hematology");
    var theUrl = index + params;
    $.ajax({
      method: "GET",
      url: theUrl,
      headers: {'api-key': "<azure-search-main-admin-key>", "Access-Control-Allow-Origin": "*"},
      contentType: "application/json",
      success: function(data) {
        alert("Search Result" + data);
      },
      error: function(jqxhr, textStatus, e) {
        alert("Error (jqxhr): " + jqxhr.responseText);
        alert("Error Status: " + textStatus);
        alert("Error (e): " + e);
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>