jQuery.ajax没有从使用不同端口号运行的Web API获取数据

时间:2016-01-05 11:02:07

标签: jquery json ajax access-control

我在asp.net 5中开发了一个Web API,我在这里获取数据库中可用的书籍列表并将其作为JSON返回。 API在Port number 5000http://localhost:5000/api/bookstore

运行

现在我在我的电脑上设置了一个网站,其中包含一个index.html文件,我正在尝试使用上述API端点。该网站在不同的端口(52786)运行。

最初使用dataType: 'json'我收到以下控制台错误:

XMLHttpRequest cannot load http://localhost:5000/api/bookstore. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:52786' is therefore not allowed access.

为避免上述'Access-Control-Allow-Origin'错误,我使用了dataType: 'jsonp',(正如Gavin here所建议的那样)。使用jsonp显然会从控制台中删除错误,但在运行页面时没有显示任何内容。我怎么知道端点是否完全被击中,以及这是不是为什么没有拉数据?

但是,当我在浏览器上单独运行http://localhost:5000/api/bookstore时,它可以完美地为我提供数据。

下面是我用来使用jQuery和ajax调用API端点的代码片段:



<script type="text/javascript">
  $(document).ready(function () {
    //jQuery.support.cors = true;
    $.ajax({
      type: "GET",
      url: "http://localhost:5000/api/bookstore",
      dataType: 'jsonp',
      success: function (data) {
        alert(data);
        $("#response").html(data);
      },
      error: function (err) {

      }
    });
  });
</script>
&#13;
&#13;
&#13;

注意:网站和Web API端口都在运行。

更新(截图)

图片1 :从其他网站调用端点时的控制台消息(可以看出我正在使用disable-web-security运行Chrome以绕过CORS。过去我成功了在开发环境中这样做也是如此。

enter image description here

图片2 :网络: enter image description here

图片3 :API来源 enter image description here

2 个答案:

答案 0 :(得分:0)

API应具有以下内容以允许跨源请求。

<httpProtocol>
      <customHeaders>
        <clear />
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="content-type" />
      </customHeaders>
</httpProtocol>

此外,请确保存在处理程序映射

<handlers>
            <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
            <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,POST,PUT" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" />
        </handlers>

答案 1 :(得分:0)

我按照以下方式开始工作。

第1步: 在Startup.csConfigureServices方法中,我们需要像这样添加CORS

public void ConfigureServices(IServiceCollection services)
{
  //CORS
  services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
}

然后我们需要将属性EnableCors添加到我们需要从不同网站外部访问的方法中,这会暴露这些方法以绕过Access-Control-Allow-Origin错误。使用CORS,我们无需运行具有禁用安全模式的浏览器!

[EnableCors("AllowAll")] //This allows the method to be called from anywhere.
public async Task<object> Recipients([FromBody] dynamic jsonText)
{
  var result = await getYourResultFromSomewhere();
  return result;
}

请告诉我这是否有任何帮助!