Перезагрузка страницы по запросу POST с использованием fetch - PullRequest
0 голосов
/ 06 марта 2020

Я пытаюсь отправить запрос на сервер node.js, чтобы отправить некоторые данные на сервер с помощью Fetch API. Теперь я хочу отобразить сообщение об успехе в соответствии с ответом, отправленным сервером обратно, но я не могу этого сделать, поскольку страница обновляется каждый раз, когда я пытаюсь это сделать , Я пробовал много разных способов остановить это (например, e.preventDefault (), изменив кнопку на div, изменив тип кнопки на кнопку вместо отправки), но ничего не работает. Пожалуйста, кто-нибудь, помогите мне. Здесь можно разместить как мой HTML, так и Javascript код. Кроме того, я очень новичок в веб-разработке (опыт только 2 месяца), поэтому, пожалуйста, не могли бы вы также сказать мне, является ли метод, которому я следую, правильным или неправильным. Спасибо!

Я использую пользовательский интерфейс Semanti c для css части

HTML код :

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
    <link rel="stylesheet" href="./styles/styles.css">
</head>

<body>
    <div class="ui fixed inverted menu">
        <div class="ui container">
            <a href="#" class="header item">
                  My Project
            </a>
        </div>
    </div>
    <div class="ui main text container">
        <form class="ui loading form" id="main_form">
            <div class="field">
                <textarea name="message" id="otp_message" cols="30" rows="10"></textarea>
            </div>
            <div class="ui success message">
                <div class="header">OTP Sent</div>
                <p>You've successfully sent the OTP on Mobile Number</p>
            </div>
            <div class="ui center aligned grid container">
                <div class="ui row">
                    <button type="submit" class="ui green button" id="btn_validate">Send</button>
                </div>
            </div>
        </form>
    </div>
</body>
<!-- <script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script> -->

<script src="./scripts/send_message.js"></script>

</html>

Javascript:

let id;
let otp;
function processUser() {
    const parameters = location.search.substring(1);
    id = (parameters.split("=")[1]);
    let url = 'http://localhost:3030/ShowContacts?id=';
    url += id;
    let data;
    fetch(url, {method:"GET"})
    .then(response => {
        if (response.status === 404) throw new Error('User not found');
        return response.text();
    })
    .then(response => {
        data = JSON.parse(response);
        // document.getElementById('name').innerText += ' ' + jsonDATA.first_name + ' ' + jsonDATA.last_name;
        // document.getElementById('phone_number').innerText += ' ' + jsonDATA.mobile_number;
        generateOTP();
    })
    .catch(e => {
        console.log(e.message);
    });
}
processUser();
async function generateOTP() {
    let url = 'http://localhost:3030/getOTP';
    fetch(url, { method: "GET" })
    .then(response => {
        if (response.status === 404) throw new Error('Unable to generate otp');
        return response.text();
    })
    .then(response => {
        const jsonDATA = JSON.parse(response);
        otp = jsonDATA.otp;
        document.getElementById('main_form').classList.remove('loading');
        document.getElementById('otp_message').value = `Hi. Your OTP is: ${otp} . Please do not share it with anybody else.`;
    })
    .catch(e => {
        console.log(e.message);
    })
}

const myForm = document.getElementById('main_form');
// const btn = document.getElementById('btn_validate');

document.forms['main_form'].addEventListener('submit', (event) => {
    event.preventDefault();
    let otpSent = false;
    const message = document.getElementById('otp_message').value;
    const raw = JSON.stringify({
        id: id,
        message: message,
        otp: otp
    });
    const requestOptions = {
        method: 'POST',
        body: raw
    };
    const url = "http://localhost:3030/otpSent";
    fetch(url, requestOptions)
    .then(response => response.json())
    .then(response => {
        otpSent =  response.success;
        if (otpSent) {
            let prevClassValue = myForm.getAttribute('class');
            prevClassValue += " success";
            myForm.setAttribute('class', prevClassValue);
        }
    })
    .catch(error => console.log(error));
})
...