【发布时间】: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 解决这个问题吗?
谢谢。
【问题讨论】: