javascript 尝试发送电子邮件并从源'null'获得对XMLHttpRequest的访问权限已被CORS策略阻止

jhkqcmku  于 2022-10-30  发布在  Java
关注(0)|答案(1)|浏览(164)

我对PHP和JS非常陌生,我有一个表单,用于将联系人信息发送到我的电子邮件,其中包含
JS文件:

$(function () {

    $("#contactForm input, #contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function ($form, event, errors) {},
        submitSuccess: function ($form, event) {
            event.preventDefault();
            var name = $("input#name").val();
            var email = $("input#email").val();
            var subject = $("input#subject").val();
            var message = $("textarea#message").val();

            $("#sendMessageButton").prop("disabled", true);
            $("#sendMessageButton span").text("SENDING...");
            $("#sendMessageButton div").removeClass("d-none");

            $.ajax({
                url: 'mail/contact-form.php',
                type: "POST",
                data: {
                    name: name,
                    email: email,
                    subject: subject,
                    message: message
                },
                cache: false,
                success: function () {
                    $('#alertMessage').html("<div class='alert alert-success alert-dismissible'>");
                    $('#alertMessage > .alert-success').html("<button type='button' class='btn-close' data-bs-dismiss='alert' aria-hidden='true'>").append("</button>");
                    $('#alertMessage > .alert-success').append("<strong>" + name + ", your message has been sent. </strong>");
                    $('#alertMessage > .alert-success').append('</div>');
                    $('#contactForm').trigger("reset");
                },
                error: function () {
                    $('#alertMessage').html("<div class='alert alert-danger alert-dismissible'>");
                    $('#alertMessage > .alert-danger').html("<button type='button' class='btn-close' data-bs-dismiss='alert' aria-hidden='true'>").append("</button>");
                    $('#alertMessage > .alert-danger').append($("<strong>").text("Sorry " + name + ", it seems that our mail server is not responding. Please try again later!"));
                    $('#alertMessage > .alert-danger').append('</div>');
                },
                complete: function () {
                    $("#sendMessageButton").prop("disabled", false);
                    $("#sendMessageButton span").text("SEND");
                    $("#sendMessageButton div").addClass("d-none");
                }
            });
        },
    });
});

$('#name, #email, #subject, #message').focus(function () {
    $('#alertMessage').html('');
});

PHP文件:

<?php
if(empty($_POST['name']) || empty($_POST['subject']) || empty($_POST['message']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
  http_response_code(500);
  exit();
}

$name = strip_tags(htmlspecialchars($_POST['name']));
$email = strip_tags(htmlspecialchars($_POST['email']));
$m_subject = strip_tags(htmlspecialchars($_POST['subject']));
$message = strip_tags(htmlspecialchars($_POST['message']));

$to = "myemail@gmail.com"; // Change this email to your //
$subject = "$m_subject:  $name";
$body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email\n\nSubject: $m_subject\n\nMessage: $message";
$header = "FROM: NoReply <noreply@noreply.com>";
$header .= "Reply-To: $email";  

if(!mail($to, $subject, $body, $header))
  http_response_code(500);
?>

当运行代码并试图发送信息到我的电子邮件,程序失败,缓存JS文件中的错误,当我检查F12,有2个错误:

Access to XMLHttpRequest at 'my PHP file location' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https, isolated-app.

和其他的:

jquery-3.6.0.min.js:2 
 POST my PHP file location net::ERR_FAILED
send    @   jquery-3.6.0.min.js:2
ajax    @   jquery-3.6.0.min.js:2
submitSuccess   @   contact-form.js:17
(anonymous) @   jqBootstrapValidation.min.js:1
dispatch    @   jquery-3.6.0.min.js:2
v.handle    @   jquery-3.6.0.min.js:2

在这一点上,我最好的猜测是,邮件服务器发生了一些问题,但我不知道我的文件中的哪一行代码是用来处理邮件服务器的。我对其他语言比服务器端脚本语言更熟悉。因此,任何来自Maven的帮助都是非常宝贵的

tv6aics1

tv6aics11#

把这段代码放在你的php文件上面。

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
    header('Access-Control-Allow-Headers: token, Content-Type');
    header('Access-Control-Max-Age: 1728000');
    header('Content-Length: 0');
    header('Content-Type: text/plain');
    die();
}

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

或者,您可以将其设为函数,并将其放在单独的文件中,例如

function cors(){
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
        header('Access-Control-Allow-Headers: token, Content-Type');
        header('Access-Control-Max-Age: 1728000');
        header('Content-Length: 0');
        header('Content-Type: text/plain');
        die();
    }

    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json');
}

并在php文件中将其命名为“新文件:cors.php

require_once('cors.php');
cors();

相关问题