0
     Код fetch-запроса в js

async auth() {
                this.isLoaing = true
                async function postData(url = '', data = {}) {
                    // Default options are marked with *
                    const response = await fetch(url, {
                        method: 'POST', // *GET, POST, PUT, DELETE, etc.
                        mode: 'cors', // no-cors, *cors, same-origin
                        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
                        credentials: 'same-origin', // include, *same-origin, omit
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        redirect: 'follow', // manual, *follow, error
                        referrerPolicy: 'no-referrer', // no-referrer, *client
                        body: JSON.stringify(data)
                    })
                    return await response.json()
                }
                postData(this.API_URL, { userLogin: this.userLogin, userPassword: this.userPassword })
                    .then((data) => {
                        console.log(data);
                    });
            }

    Обработчик в PHP

function checkAuth() {
    $body = json_decode(file_get_contents('php://input'), true);
    $stmt = pdo()->prepare('SELECT * FROM `users` WHERE `userLogin` = :userLogin');
    $stmt->execute([
        'userLogin' => $body['userLogin'],
    ]);
    if(!$stmt->rowCount()){
        header('HTTP/1.1 500 Authorisation error');
        header('Content-Type: application/json; charset=UTF-8');
        die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
    } else{
    $user = $stmt->fetch();
    header('Content-Type: application/json; charset=UTF-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: *'); 
    header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE');    
    $json = json_encode($user, JSON_UNESCAPED_UNICODE);
    echo $json;
    }
    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            echo 'Ошибок нет';
        break;
        case JSON_ERROR_DEPTH:
            echo 'Достигнута максимальная глубина стека';
        break;
        case JSON_ERROR_STATE_MISMATCH:
            echo 'Некорректные разряды или несоответствие режимов';
        break;
        case JSON_ERROR_CTRL_CHAR:
            echo 'Некорректный управляющий символ';
        break;
        case JSON_ERROR_SYNTAX:
            echo 'Синтаксическая ошибка, некорректный JSON';
        break;
        case JSON_ERROR_UTF8:
            echo 'Некорректные символы UTF-8, возможно неверно закодирован';
        break;
        default:
            echo 'Неизвестная ошибка';
        break;
    } 
}

Причем в Postman данные отправляются нормально и status: 200. Подскажите, что делать, я уже замучался

Ошибки:

Access to fetch at 'http://anteiserver:8080/api/core/function.php' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
        
        
POST http://anteiserver:8080/api/core/function.php net::ERR_FAILED
postData @ AuthForm.vue:27
auth @ AuthForm.vue:41
(анонимный) @ AuthForm.vue:56
(анонимный) @ runtime-dom.esm-bundler.js:1483
callWithErrorHandling @ runtime-core.esm-bundler.js:173
callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:182
invoker @ runtime-dom.esm-bundler.js:345
                        
Uncaught (in promise) TypeError: Failed to fetch
    at postData (AuthForm.vue:27:40)
    at Proxy.auth (AuthForm.vue:41:13)
    at AuthForm.vue:56:63
    at runtime-dom.esm-bundler.js:1483:16
    at callWithErrorHandling (runtime-core.esm-bundler.js:173:22)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:182:21)
    at HTMLFormElement.invoker (runtime-dom.esm-bundler.js:345:9)

Консоль ошибок

Запрос в Postman

15

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.