【问题标题】:Reason: CORS header 'Access-Control-Allow-Origin' missing [duplicate]原因:CORS 标头“Access-Control-Allow-Origin”缺失 [重复]
【发布时间】:2017-01-09 08:25:02
【问题描述】:

我正在使用 XMLHttpRequest 用 javascript 运行 ajax。我收到错误

“原因:CORS 标头 'Access-Control-Allow-Origin' 缺失”。

我正在访问 Ajax 中的其他域 url。这是我的代码

if (mypostrequest.readyState==4){
                console.log(mypostrequest.status);
              if (mypostrequest.status==200 || window.location.href.indexOf('http')==-1){
               console.log('got it');
               console.log(mypostrequest.responseText);
               redirect_url = mypostrequest.responseText;
               //BTHit();
              }
              else{
               console.log('cant get data');
              }
}
var parameters='campaign_id='+campaign_id;
        mypostrequest.open('POST', 'http://mydserverip/get_campaign.php', true)
        mypostrequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        //mypostrequest.setRequestHeader('Access-Control-Allow-Origin', '*');
        mypostrequest.send(parameters);

在我的服务器上,我只是打印数据,例如

<?php male('myemail','test','testm');  echo "hello"; ?>

我收到了电子邮件,但是当我查看控制台时出现上述错误,但没有任何响应。

console.log(mypostrequest.status) 的输出;为 0,控制台显示无法获取数据。

我尝试了很多谷歌的解决方案,但都无法解决我的问题。

我也试过 .htaccess,但运气不好。

请帮帮我。

【问题讨论】:

    标签: ajax xmlhttprequest cors


    【解决方案1】:

    我的 API 也有同样的问题。在您的 PHP 应用程序中,您需要添加标头以允许 CORS。使用header函数。

    header('Access-Control-Allow-Origin: *')
    

    上一行允许从任何域访问您的 php 应用程序。 您可以通过添加来源来限制您的域访问。

    header('Access-Control-Allow-Origin: http://exemple.com/myapp http://foobar.com/api')
    

    如果您只想要某种方法来访问您的服务器(例如 GET 或 POST only ) 也添加这些行

    header('Access-Control-Allow-Methods:' . $YourMethods)
    

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 2019-06-19
      • 1970-01-01
      • 2021-12-02
      • 2021-02-11
      相关资源
      最近更新 更多