AngularJs中的CORS请求


CORS request in AngularJs

我在php上创建了一个邮件服务,这个服务发送信件给一些用户。下面是一个代码:

<?php
require 'vendor/autoload.php';
header('Content-type : application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: X-Requested-With, content-type');
$response = array(
      'text' => '');
if(!empty($_POST)){
$json = json_decode($_POST["req"]);
$key     = $json->key;
$sub     = $json->subject;
$toemail = $json->emailTo;
$FromEmail   = $json->emailFrom;
$html    = $json ->html;
$sendgrid = new SendGrid($key);
$email    = new SendGrid'Email();
$email->addTo($toemail)
      ->setFrom($FromEmail)
      ->setSubject($sub)
      ->setHtml($html);
$sendgrid->send($email);
$response['text'] = 'Email was sent from '.$FromEmail.' to'. $toemail.'. Success.';
}else{
$response['text'] = 'Sorry! $_POST is undefind';
}
echo json_encode($response);
?> 

我需要使用Angular.js创建一个跨域请求到这个服务。下面是我的代码:

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
app.controller("emailCtrl", function ($scope, $http) {
    var dataForAdminNewsletter = angular.toJson({
        key: "********************************************",
        subject: "New Email",
        emailTo: "mail1@mail.com",
        emailFrom: "mail1@mail.com",
        html: 'You have a new subscriber' + $scope.emailField
    });
    $scope.sendPost = function () {
        $http({
            url: 'http://my.azurewebsites.net/mail.php',
            method: "POST",
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            data: {
                "req": dataForAdminNewsletter
            }
        });
    }
});

结果我得到了下一个错误:XMLHttpRequest无法加载my.azurewebsites.net/mail.php。对预飞行请求的响应没有通过访问控制检查:请求的资源上没有"access - control - allow - origin"标头。

我不能更改服务器端的代码。有人能帮我解决Angular的这个问题吗?

谢谢。

我在apache虚拟主机配置中使用这些行,

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} OPTIONS 
    RewriteRule ^(.*)$ $1 [R=200,L]
</IfModule>
 <IfModule mod_headers.c>
    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS"
 </IfModule>

作为魅力,也许这有帮助。

简单地说——你不能。

CORS应该在服务器中为angular服务启用,或者实际上为任何与之通信的外部服务启用。

裁判:https://gist.github.com/mlynch/be92735ce4c547bd45f6

使用fiddler或chromium devTools检查请求和响应。

服务器的响应应该有CORS报头。修改angular的服务请求不会有任何好处

另外,您可以查看此链接- https://forum.ionicframework.com/t/http-no-access-control-allow-origin-problem-on-post/5625/6