【问题标题】:Using JavaScript to hit web service running in Azure使用 JavaScript 访问在 Azure 中运行的 Web 服务
【发布时间】:2014-06-12 14:47:13
【问题描述】:

我有一个运行我的 Web UI 的 Azure ASP.Net Web 角色。我有一个 MvC4 REST API 在同一个 Azure 实例中以单独的 Web 角色运行。 Azure 将 Web UI 放在端口 80 上,将 API 放在端口 8080 上。因此,当我想从网页向 REST API 发送 AJAX 请求时,我需要修改 URL 以更改端口以连接到 REST API Web UI Web 角色。

我的页面中有这个 JavaScript:

    function getWebAPIURL(criteria) {
      //      The generated code had this:
      //        var uri = 'api/values';
      //  But that only works if the API is running in the same Azure web role as the UI,
      //  which it isn't - it's running in the same domain but on port 8080.  So we have
      //  to munge the URL a bit to get the correct URL for the RESTful API

      var strWebAPIURL =    window.location.protocol + '://' +
                            window.location.hostname + ':8080' +
                            '/api/values';

      // If provided,critiera is appended in REST style, e.g api/values/5
      if (criteria != undefined && criteria != null && criteria != '') {
          strWebAPIURL = strWebAPIURL + '/' + criteria;
      }
      // console.log(strWebAPIURL);
      return strWebAPIURL;
  }

  $(document).ready(function () {
      // Send an AJAX request
      $.getJSON(getWebAPIURL())
          .done(function (data) {
              // On success, 'data' contains a list of files.
              $('#File').text(formatReturnedItems(data));
          });
  });

当我在调试器中停止时,我看到从 getWebAPIURL 返回的 URL 是(正确的,我相信)

http://xxxx.cloudapp.net:8080/api/values

但我从 getJSON 调用中返回了 404 错误。当我查看 Fiddler 时,我看到该 URL 显然要转到

即它继续使用 主域 作为基础,并将我的 xxxx.cloudapp.net:8080 作为 URL 的子部分。我相信这与防止跨域调用有关。

但这似乎是一个非常常见的情况 - 我有一个 Web UI 和一个 REST API 层。看起来我并不想在这里做一些真正奇怪的事情,这应该很难——所以我觉得我只是在做一些简单的错误。

其他人会这样做吗?

【问题讨论】:

    标签: javascript asp.net asp.net-mvc-4 rest azure


    【解决方案1】:

    window.location.protocol 将返回带有尾随冒号 (ref) 的协议。因此没有必要将它包含在您的 JavaScript 中。

    var strWebAPIURL = window.location.protocol + '//' +
                       window.location.hostname + ':8080' +
                       '/api/values';
    

    上面的代码将创建一个有效的 URL,这样 jQuery $.getJSON() 函数就不会觉得有必要改变它了。

    【讨论】:

    • 因为没有钉子……这就是问题所在。我没有仔细看,看不到 URL 实际上有一个额外的“:”......过度思考问题。谢谢!
    猜你喜欢
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    相关资源
    最近更新 更多