无法使用 jquery POST 查询 Azure 搜索

Unable to query Azure Search using jquery POST

我将我尝试查询的 Azure 搜索索引的 CORS 设置为 "All",并且还向索引命中的 blob 存储添加了“*”。我尝试了各种查询参数/选项,但仍然 运行 进入 "No 'Access-Control-Allow-Origin' header" 错误。我 运行ning 来自 Eclipse,一个 tomcat 服务器,java Web 应用程序,它调用 javascript 函数。我正在为搜索服务传递 api-key 并设置 headers;这是哪里出了问题?我还尝试将 Web 应用程序部署到同一数据中心和同一资源组中 Azure 中的虚拟机,但仍然出现相同的错误。我试过将 beforeSend 函数也添加到 ajax 调用中,但没有帮助。

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);
    }
});

浏览器错误: XMLHttpRequest 无法加载 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' 因此不允许访问。响应具有 HTTP 状态代码 400。

这似乎不是 CORS 问题(如 400 错误所示)。看起来您混淆了 Search API 的 GET 和 POST 版本的格式。具体来说,您在查询字符串上有 search 参数,显然没有请求正文。如果您想在查询字符串上发送搜索参数,请将动词更改为 GET。

要解决此问题,您可以尝试以下方法:

  1. 正如 Bruce Johnston 所说,将动词更改为 GET
  2. 使用函数 encodeURI 而不是 encodeURIComponent 对查询字符串进行编码。

代码如下:

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>

我认为您必须将 api 密钥放入 url

 var url = 'https://NAME.search.windows.net/indexes/INDEX-NAME/docs?api-version=2015-02-28&highlight=description&fuzzy=true&api-key=YOURAPIKEY&search='+searchString;

此外,POST 请求的 url 略有不同,它在 url 的末尾包含一个额外的路由部分“/search”。 https://docs.microsoft.com/en-us/rest/api/searchservice/search-documents