【问题标题】:Stuck on CORS Problems卡在 CORS 问题上
【发布时间】:2015-11-19 13:55:49
【问题描述】:

我查看了很多关于在 AJAX 中请求“GET”时出现的“Access-Control-Allow-Origin”问题的 StackOverflow 问题。

我通过创建一个简单的 PHP 脚本来提供 HTML 文件 (<?php include_once("home.html"); ?>),将一个简单的静态应用程序部署到 Heroku。

索引.php

<?php header("Access-Control-Allow-Origin: *"); 
      header("Access-Control-Allow-Credentials: true "); 
      header("Access-Control-Allow-Methods: OPTIONS, GET, POST"); 
      header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control"); 
      include_once("home.html"); ?> 

home.html

只是一个静态 html 文件。 js文件:

$.ajax({ url: 'http://example.com', 
         type: 'GET', 
         crossDomain: true, 
         success: function(res) { 
                   console.log("hello"); 
                  } 
         })

我的网站使用 AJAX 提取图像。我已尽我所能让我的网站允许 CORS,但没有任何效果。我尝试过像header("Access-Control-Allow-Origin: *"); 那样更改我的标题,甚至尝试编辑我的.htaccess 文件。

我被困住了。我将不胜感激。

【问题讨论】:

  • 为什么要使用ajax来获取图片?
  • @deefour -- 不止于此,有点像网络爬虫。
  • 有很多相关的细节你没有提供。帮助我们帮助您。详细描述您的设置。显示代码。准确地展示你做了什么。准确显示您遇到的错误。
  • index.php:&lt;?php header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Credentials: true "); header("Access-Control-Allow-Methods: OPTIONS, GET, POST"); header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control"); include_once("home.html"); ?&gt;home.html 只是一个静态 html 文件。 js文件:$.ajax({ url: 'http://example.com', type: 'GET', crossDomain: true, success: function(res) { console.log("hello"); } })
  • @deefour 还有什么想要的吗?错误:“XMLHttpRequest 无法加载 example.com。请求的资源上不存在 'Access-Control-Allow-Origin' 标头。因此不允许访问源 'example.com'。”

标签: ajax cors


【解决方案1】:

您不能同时使用凭据和*。如果要在请求中使用凭据,则需要在服务器上明确列出请求来源。例如,Access-Control-Allow-Origin: example.com

【讨论】:

    猜你喜欢
    • 2019-05-21
    • 2017-04-19
    • 2014-12-16
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多