繁体   English   中英

如何在 PHP 中向通过 javascript fetch API 发出的请求发送响应?

[英]How to send a response in PHP to a request made through the javascript fetch API?

我有一个 PHP 应用程序,它从另一个域中的客户端接收数据。 数据通过 POST 方法从 fetch API 到达,但 PHP 不会向 fetch API 发送响应。

foo.com/endpoint.php:

<?php
include_once('database/connection.php');
header('Content-Type: application/json');

$ip = $_POST["ip"];
$city = $_POST["city"];
$state = $_POST["state"];
$country = $_POST["country"];
$category = $_POST["category"];
// Checking if the req ip already have registered other req
$ip_query = "SELECT * FROM registers WHERE `ip` = '$ip'";
$ip_result = mysqli_query($conn, $ip_query);
$ip_check = mysqli_fetch_assoc($ip_result);
if (!$ip_check) {
    // registering data after validation
    $new_query = "INSERT INTO `registers` (`ip`, `city`, `state`, `country`, `category`, `created`) VALUES ('$ip', '$city', '$state', '$country', '$category', '2022-07-21 00:00:01')";
    $new_create = mysqli_query($conn, $new_query);
    $result = array(
        'ok' => true,
        'status' => 200
    );
    // sending response
    http_response_code(200);
    echo json_encode($result);
} else {
    // sending response if already registered
    http_response_code(503);
}

客户端获取代码:

fetch(this.url, {
                method: 'POST',
                mode: 'no-cors',
                body: this.getFormValues(),
                headers: {
                    "Accept": "application/json",
                    'Content-Type': 'application/json'
                  }
            })
            .then(resp => resp.json())
            .then(data => {
                console.log(data)
                if (data.ok) {
                    this.Metrics.setSent()
                } else {
                    throw Error(r.statusText)
                }
            })
            .then(() => {
                this.Metrics.setSent()
                this.Metrics.dismiss()
            })
            .catch(erro => {
                console.log("Erro: ",erro)
                this.Metrics.dismiss()
            });

存储数据没关系,我的问题只是发送响应:(

PHP 不会自动将 POST 正文解析为 JSON。 要解决此问题,您必须将json_decode()添加到您的代码中,如下所示:

$ip = json_decode($_POST, true)["ip"];

我没有注意到当使用“no-cors”模式发出请求时,我会得到一个不透明的响应。

我刚刚将下面的代码添加到我的 PHP 文件的开头,将获取模式更改为“cors”,一切都按预期工作:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header("Access-Control-Allow-Credentials: true");
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
     header('Access-Control-Allow-Origin: *');
     header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization") ;
     header("HTTP/1.1 200 OK");
     die();
}

我进行了@brrrrrrr 建议的修改并更新了查询以防止 SQL 注入。

谢谢大家。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM