【问题标题】:ajax GET - XMLHttpRequest cannot loadajax GET - XMLHttpRequest 无法加载
【发布时间】:2014-12-09 13:42:13
【问题描述】:

我正在尝试从外部 api 获取数据,但是 我不断收到错误消息:

XMLHttpRequest 无法加载...请求的资源上没有“Access-Control-Allow-Origin”标头。

这是我的代码:

    <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
    <script type="text/javascript">
        (function () {
            $.support.cors = true;
            $.ajax({
                type: "GET", url: "http://zhettoapi.azurewebsites.net/api/Values?product=Coca Cola", success: function (data) {
                    window.alert("" + data);
                    //example of setting innerHTML of object
                    document.getElementById("myElement").innerHTML = "The number is:" + data;
                }, error: function (xhr, status, error) {
                    // Display a generic error for now.
                    alert("Error: " + xhr + "   " + status + "   " + error);
                }
            });
        })();
    </script>
</head>
<body>
    <div id="myElement"></div>
</body>
</html>

【问题讨论】:

标签: javascript ajax html azure asp.net-web-api


【解决方案1】:

由于我可以看到 use 使用了 Get url ("http://zhettoapi.**azurewebsites**.net/api/Values....) 中提到的 azurewebsites,并且我对此有一些经验,所以我想解决您的问题,即使这个问题没有标记为 Azure .

假设:您已经使用了WebAPI。并作为网站部署在 Azure 上。 (我确定,确实如此)。

由于您尝试以 ajax.get 请求的形式从其他域访问 Azure Web API url,因此由于 cross domain (CORS) 安全性而被阻止。所以这里的第一件事是启用它(托管的 WebAPI 项目)CORS。

启用 CORS 的步骤:

  1. 安装这个 - 使用 NuGet 安装包 Microsoft.AspNet.WebApi.Cors
  2. 打开文件 App_Start/WebApiConfig.cs。将以下代码添加到 WebApiConfig.Register 方法中。
  3. 接下来,将 [EnableCors] 属性添加到 Controller 类:

    有以下参数

    [EnableCors(origins: "http://zhettoapi.azurewebsites.net", headers: "", methods: "")]

  4. 重新部署您的 WebAPI 项目。

来源 - http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

更多链接 - http://www.codeproject.com/Articles/742532/Using-Web-API-Individual-User-Account-plus-CORS-En

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 2015-04-15
    • 1970-01-01
    • 2016-10-02
    • 2011-11-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多