AngularJs 中的 CORS 请求

Posted

技术标签:

【中文标题】AngularJs 中的 CORS 请求【英文标题】:CORS request in AngularJs 【发布时间】:2016-10-30 16:32:28 【问题描述】:

我在 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”标头。因此不允许访问 Origin 'localhost:11708'。

我无法更改服务器端的代码。有人可以帮我用 Angular 解决这个问题吗?

谢谢。

【问题讨论】:

【参考方案1】:

我在 apache 虚拟主机 conf 中使用这一行,

<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>

它就像魅力一样,可能是这个帮助。

【讨论】:

谢谢,但我已经在我的服务器端添加了这些标题: header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS'); 第一部分很重要。 是的,我也加了:header('Access-Control-Allow-Origin: *'); 然后,需要通过请求方式添加header。否则,您可以按照我给出的解决方案使用 apache conf 处理【参考方案2】:

简单地说-你不能。

应该在服务器中为角度服务启用CORS,或者事实上任何外部服务都应该与之通信。

参考:https://gist.github.com/mlynch/be92735ce4c547bd45f6

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

来自服务器的响应应具有 CORS 标头。 更改角度服务请求不会有任何好处

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

【讨论】:

我在服务器端添加了 header('Access-Control-Allow-Origin: *') 。你是什​​么意思:“改变角度服务请求不会有任何好处”?

以上是关于AngularJs 中的 CORS 请求的主要内容,如果未能解决你的问题,请参考以下文章

AngularJS 中的跨域 HTTP 请求失败

AngularJS 和 Laravel - 跨域 CORS / XHR 请求缺少(记住)cookie

如何处理 Spring Boot、AngularJS 应用程序中的 CORS 错误?

AngularJS 和 Laravel - CORS

angularjs + PHP应用程序中的CORS错误

rails-api 和 angularJs 中的 CORS