Javascript код не отправляет кастомные request заголовки

Рейтинг: 0Ответов: 1Опубликовано: 11.07.2023

Создаю пробное API на php 8.0 и apache2. Столкнулся с проблемой, что php не воспринимает кастомные headers, созданные мною в js

async function functionToUpdate() {

const url = 'http://*ip*:8080/php/index.php';

const data = {
    email:'Frog@mail.ru',
    password:'password',
    phone:'+7123312344213',
    login:'Harry'
}

const headers = new Headers();
headers.append('Content-Type','application/json');
headers.append("RequestType","registration");
fetch(url, {
    method:"POST",
    headers:headers,
    body: JSON.stringify(data)
})
.then(responce => responce.json())
.then(data => console.log(data))
.catch(error => console.error(error));
/*const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('RequestType','registration');
xhr.setRequestHeader('Content-Type','application/json');
xhr.onreadystatechange == function() {
    if(xhr.readyState === 4 && xhr.status === 200){
        var response = JSON.parse(xhr.responseText);
        console.log(response);
    }
};

}

php код

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTION');
header("Access-Control-Allow-Headers: *");
header("Access-Control-Request-Headers: authorisation-token,device_id,session_id");
header('Content-type: json/application');
header('Connection: Close');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

$type = getallheaders()['RequestType'];

if ($type === 'registration') {

    $login = getClearElement($_POST['login']);

    $password = getClearElement($_POST['password']);

    $phone = getClearElement($_POST['phone']);

    $postEmail = getClearElement($_POST['email']);


    require_once "./post/registration.php";
} 

Проблема в том, что php код не видит RequestType ни в каком виде. Сам запрос воспринимается, однако header не виден. Даже в браузере не отображается.

Однако, если осуществлять данный запрос через postman, указывая в Headers RequestType, то код будет работать и обрабатывать.

Ответы

▲ 0

Спустя несколько дней

Внезапно код заработал. В php ничего не менял. Однако в js использовал вот такой код.

async function functionToUpdate() {

const url = 'http://*ip*:8080/php/index.php';

var RequestType = "registration";
var xhr = new FormData();
xhr.append('email', 'Frog@mail.ru');
xhr.append('password', 'password');
xhr.append('phone', '+123123123');
xhr.append('login', 'Froggger');

var xx = new XMLHttpRequest();
xx.open('POST',url,true);
xx.setRequestHeader('RequestType', 'registration');
xx.onload = function() {
    console.log(this.responseText);
}
xx.send(xhr);
}

Теперь регистрация проходит успешно.