【问题标题】:XMLHttpRequest - Ajax request - No 'Access-Control-Allow-Origin' header is presentXMLHttpRequest - Ajax 请求 - 不存在“Access-Control-Allow-Origin”标头
【发布时间】:2015-11-18 09:10:35
【问题描述】:

问题背景:

我有一个带有单个视图的基本 MVC 应用程序,它使用 AJAX 请求来调用我在 Azure 中托管的一个简单的 WepApi 应用程序。 WebApi 用于呈现在 AJAX 请求的 Success 方法中打开的 pdf 文档。

问题:

当我调用 WebApi url 时,我在 Chrome 的控制台中收到以下错误:

XMLHttpRequest cannot load http://xxxxxxx.azurewebsites.net/api/PdfHandler/PdfButtonCaller.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:1570' is therefore not allowed access.
The response had HTTP status code 405.

我已添加 Chrome Allow Control Origin Control 插件。

守则:

包含 AJAX 请求的 MVC 视图:

@{
ViewBag.Title = "PdfButtonCaller";
}

<script src="~/Scripts/jquery-1.8.2.min.js"></script>

<h2>PdfButtonCaller</h2>

<button id="pdfClick">Click this</button>

<script>
    $(document).ready(function () {

        $('#pdfClick').click(function () {

            alert('clicked');

            $.ajax({
                type: "POST",
                url: 'http://xxxxxxx.azurewebsites.net/api/PdfHandler/PdfButtonCaller',
                cache: false,
                contentType: 'application/pdf',
                success: function (response) {
                    alert('worked');
                    window.open('http://xxxxxxx.azurewebsites.net/api/PdfHandler/GetPdf');
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert('Error'+ textStatus, errorThrown);
                }
            });
        });
    });
</script>

WebApi 控制器:

public class PdfHandlerController : ApiController
{
    [System.Web.Http.HttpPost]
    public void PdfButtonCaller()
    {
        var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/readme.pdf");

        byte[] bytes = System.IO.File.ReadAllBytes(fullPath);
    }

    [System.Web.Http.HttpGet]
    public HttpResponseMessage GetPdf()
    {
        var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/readme.pdf");

        byte[] bytes = System.IO.File.ReadAllBytes(fullPath);

        var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
        response.Content = new ByteArrayContent(bytes);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
        return response;
    }
}

任何帮助解决此 XMLHttpRequest 请求错误将不胜感激。

【问题讨论】:

  • 请在 StackOverflow 上快速搜索这个问题 - 这个问题已经回答了很多次了。
  • 每天都会出现问题...谷歌该错误...您应该在此处发布问题之前完成此操作
  • 了解同源策略和 CORS

标签: javascript jquery ajax asp.net-web-api


【解决方案1】:

在您的 API 中,您需要将 access-control-allow-origin 标头设置为您的域名或“*”。如果您将其设置为您的实时域,那么如果您想进行测试,您还必须将其设置为 localhost。不过,指定星号可能是最简单的方法,这样任何域都可以使用您的 API。

https://msdn.microsoft.com/library/azure/7406a8ce-5f9c-4fae-9b0f-e574befb2ee9#SetHTTPheader

<set-header name="access-control-allow-origin" exists-action="skip">
    <value>*</value>
</set-header>

或者……

Response.AppendHeader("Access-Control-Allow-Origin", "*");

这里是关于 CORS 标准的更多信息:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

【讨论】:

  • @ Joshua Dannemann 感谢您为我提供了一个实际的答案,而不是告诉我“去搜索该网站”......好像我已经没有了。你用这个答案让我走上了正确的轨道。我通过包管理器控制台实现了 CORS,然后在每个 Web api 方法上显式设置访问权限,以允许来自本地主机 MVC 站点的请求。
  • 不客气。并感谢您接受我的回答以回报您的青睐!
猜你喜欢
  • 2019-08-15
  • 2014-09-22
  • 2019-03-08
  • 2015-04-04
  • 2017-08-20
  • 1970-01-01
  • 2019-02-28
  • 2018-07-09
相关资源
最近更新 更多