任何PHP请求返回502 Bad Gateway

时间:2019-11-24 07:53:02

标签: javascript php

我决定编写一个小的php脚本来发送电子邮件。而且我遇到了一个问题-当我从PHPMailer类通过$mail->send()发送请求时,我得到了错误的Gateway502。此后,脚本冻结并且不响应请求。即使更改了emailSender.php中的代码,也不会发生任何事情。即使echo命令也不起作用。

当我重新启动本地服务器时,脚本再次响应,但再次返回502。来自$_POST["EmailRecipient"]$_POST["Message"]请求的数据正确输入,并且也通过回显正确输出。我可以在控制台中看到它。

然后我尝试在google.com上提出请求,并再次收到502错误的网关。 我究竟做错了什么?这是我的第一个php代码,我无法弄清楚。

我在phpstorm的本地主机上的一个文件夹中运行了所有文件。请解释我做错了。下面是我的代码。

function processForm() {
    let emailRecipient = document.getElementsByName('EmailRecipient')[0].value;
    let emailMessage = document.getElementsByName('Message')[0].value;

    if (checkEmail(emailRecipient) && emailMessage) {
        let form = document.getElementById('emailForm');
        let formData = new FormData(form);

        postRequest('emailSender.php', formData);
        return false;
    }
    else {
        showMessage('You have entered an invalid email address!');
        return false;
    }
}

function postRequest(url, data) {
    fetch(url, {
        method: 'POST',
        mode: 'no-cors',
        cache: 'no-cache',
        body: data
    })
        .then(handleErrors)
        .then(response => showMessage(response.text()))
        .catch(error => showMessage(error));
}

function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }

    return response;
}

function showMessage(responseText) {
    console.log(responseText);
}

function checkEmail(email) {
    let regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    return regex.test(email);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <form id="emailForm">
            <div>
                <p>To:</p>
                <input type="text" name="EmailRecipient">
            </div>
            <div>
                <p>Message:</p>
                <textarea name="Message"></textarea>
            </div>
            <div>
                <input type="submit" name="SendEmail" onclick="return processForm();">
            </div>
        </form>
    </div>
</body>

<script src="formHandler.js"></script>

</html>

<?php

$emailRecipient = '';
$message = '';

if (isset($_POST["EmailRecipient"]) && isset($_POST["Message"])) {
    $emailRecipient = $_POST["EmailRecipient"];
    $message = $_POST["Message"];

    echo $emailRecipient;
    echo "\n";
    echo $message;
}

$sFile = file_get_contents("http://www.google.com"); // 502 bad gateway

echo "\n";
echo $sFile; 

1 个答案:

答案 0 :(得分:0)

不是很清楚服务器设置和phpstorm。我认为它会在安装过程中自动拉起服务器及其配置。不过,他通常在本地主机上运行简单的脚本,而没有任何请求。但是事实证明,phpstorm需要手动配置。到目前为止,我已经为自己找到了出路:从服务器根文件夹处理项目。在我的情况下,这是XAMPP,路径是C:\ xampp \ htdocs。如果从那里运行项目,则请求将正确执行。 看来您也可以从任意目录配置映射。