Access-Control-Allow-Origin不允许使用Origin域名

Origin domain.com is not allowed by Access-Control-Allow-Origin

本文关键字:Origin 域名 不允许 Access-Control-Allow-Origin      更新时间:2023-09-26

Access-Control-Allow-Origin不允许获取"Origin http://domain.com "。"错误。我想做的是我有一个新闻通讯系统,我在一个子域名和另一个子域名的新闻通讯。当用户输入不正确的电子邮件并提交信息时,代码工作正常,但是它不会显示"成功,电子邮件发送消息",并且我在提交时得到错误。

$('#submitButton').click(function(e) {
        var ap = $('.appear-first:eq(0)').fadeOut(200);
        if ($('#email').val() === '' || $('#email').val().search('@') == -1){
            ap.css('color','#f00').text('Please enter a valid Email Address.').fadeIn(300);
            e.preventDefault();
        } else {
            var a = $('#subscribeform');
            console.log(a);
            $.post('http://domain.domain.com/?p=subscribe&id=1', a.serialize(), function(re) {
                console.log(re);
                ap.css('color','#fff').text('Thank you for subscribing to our newsletter. You will be emailed shortly to confirm your address.').fadeIn(300);
            });
        }
        e.preventDefault();
    });
});

谢谢。

浏览器将发送一个飞行前请求,通过检查响应头来检查所请求的域是否允许CORS

您所请求的域应该知道您所请求的域。

那么在domain.com上实现如下代码(PHP示例):

$allowed_domains = array("http://sub.domain.com");
if (isset($_SERVER['HTTP_ORIGIN'])
  && in_array($allowed_domains, $_SERVER['HTTP_ORIGIN'])) {
    // emit CORS header
    header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
    // enable session/cookies
    header('Access-Control-Allow-Credentials: true');
    // optional headers here
    header("Access-Control-Allow-Headers: Content-Type");
}
if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    // CORS pre-flight request, we don't need to do anything else
    exit;
}