@savva09
Начинающий .NET-ер

Я точно правильно понял cookies? Откуда столько редиректов?

Почему-то при запуске приложения происходит куча редиректов от index.html до Main/main.html и обратно. В итоге в main.html в id=login вижу false.

index.html

<body>
    <script>
        const cookies = document.cookie.split(';');
        cookies.forEach((elem) => {
            if (elem.startsWith("auth=")) window.location.href = "Main/main.html";
        })
    </script>
    <div class="container-where">
        <h1>Tasking</h1>
    </div>
    <div class="container">
        <div class="container2">
            <h1>Hello!</h1>
            <form name="first" action="https://localhost:7182/api/login/Login">
                <table class="login-table">
                    <thead>
                        <tr><td><h2>Please log in</h2></td></tr>
                    </thead>
                    <tbody>
                        <tr><td><input type="text" name="login" id="login" placeholder="login" required /></td></tr>
                        <tr><td><input type="text" name="password" id="password" placeholder="password" required /></td></tr>
                        <tr><td><p id="error" class="errorMessage" hidden>You might not see this window</p></td></tr>
                        <tr><td><input type="submit" value="Send" style="width: 100%;" /></td></tr>
                    </tbody>
                </table>
            </form>
        </div>
    </div>
    <!-- Error-showing script -->
    <script>
        const urlParams = new URLSearchParams(window.location.search);
        const errParam = urlParams.get('err');
        const errorP = document.getElementById("error")
        if (errParam === '0') {
            errorP.hidden = false;
            errorP.innerHTML = "User was not found";
        } else if (errParam == '1') {
            const loginParam = urlParams.get('login');
            const inputElement = document.querySelector('#login');
            inputElement.value = loginParam;
            errorP.hidden = false;
            errorP.innerHTML = "Password is incorrect";
        }
    </script>
</body>



Main/main.html

<body>
    <div class="main-container">
        <table>
            <thead>
                <tr>
                    <td><h1>Your tasks</h1></td>
                </tr>
                <tr>
                    <th class="bottom-bordered"><h4>Date</h4></th>
                    <th class="left-bordered bottom-bordered"><h4>Task</h4></th>
                </tr>
            </thead>
            <tbody id="main-body">
            </tbody>
        </table>
    </div>

    <div class="heading-container">
        <div class="container-where">
            <div class="logo-undercover">
                <h1 class="logo-label">Tasking</h1>
            </div>
        </div>
        <div class="container-who">
            <table>
                <tbody>
                    <tr>
                        <td class="icon-undercover non-main"><img class="icon" alt="icon" src="../static/user-icon.jpg" /></td>
                        <td class="non-main"><h3 id="login">123</h3></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <script src="main.js"></script>
    <script src="setTasks.js"></script>
</body>



Виновники по моему мнению:
main.js

var auth = false;
const cookies = document.cookie.split(';');
cookies.forEach(element => {
    if (element.startsWith('auth=')) auth = element.substring(5);
});
if (auth == false) window.location.href = '../index.html';

var login = document.getElementById('login');
login.innerText = auth;



не думаю что как-то влияет
setTasks.js

const table = document.getElementById("main-body");
table.innerHTML = "<h3>Loading...</h3>"

document.cookie = "loaded=0";

async function run() {
    fillNext();
}

async function fillNext() {
    let loaded = Number(document.cookie.split(";").find((elem) => { elem.startsWith("loaded=") }).substring(6));

    const response = await fetch("https://localhost:7182/api/Tasking/GetFrom?index=" + loaded + "&count=10");

    const tasks = await response.json();

    let template = {
        Year: "",
        Month: "",
        Day: "",
        Mess: "",
        render: function () {
            return "<tr>" +
                "<td class=\"bottom-bordered\"><p>" + this.Day + "." + this.Month + "." + this.Year + "</p></td>" +
                "<td class=\"left-bordered bottom-bordered\"><p>" + this.Mess + "</p></td>" +
                "</tr >"
        }
    }

    let html = "";

    tasks.forEach((elem) => {
        template.Year = elem.createdAt.substring(0, 4);
        template.Month = elem.createdAt.substring(5, 7);
        template.Day = elem.createdAt.substring(8, 10);
        template.Mess = elem.taskText;
        html += template.render();
    })

    table.innerHTML += html;

    document.cookie = "loaded=" + (loaded + 10);
}


run().then(() => {
    if (table.innerHTML == "") {
        table.innerHTML = "<h3>Nothing to view!</h3>"
    }
});



Где я добавляю cookies? на сервере:
Asp-action

// После верификации пароля
Response.Cookies.Append("auth", login);
Response.Cookies.Append("pass", password);

return Redirect("https://localhost:7182/Main/main.html");



Также на сервере все запросы логгируются:
log

Now: 10.01.2024 14:22:05, From: localhost:7182, To: Requested to Login controller, cookies: Microsoft.AspNetCore.Http.RequestCookieCollection, message: Login attempt
Now: 10.01.2024 14:22:05, From: localhost:7182, To: Requested to Login controller, cookies: Microsoft.AspNetCore.Http.RequestCookieCollection, message: Verification successed login: savva, password: savva
Now: 10.01.2024 14:22:08, From: localhost:7182, To: Requested to Tasking controller, cookies: Microsoft.AspNetCore.Http.RequestCookieCollection, message: Get count=10 request. Exists: 0


подробнее о проблеме:
Когда я загружаю страницу с чистыми cookies, все хорошо, меня никуда не перекидывает, спокойно логинюсь, никаких переадресаций. Но если перезагрузить main.html, то начинается эта куча редиректов туда-обратно. То же происходит при загрузке страницы с сохраненными cookies. И в итоге меня выкидывает либо на страницу логина, либо на страницу main.html где логин=false
  • Вопрос задан
  • 100 просмотров
Пригласить эксперта
Ответы на вопрос 1
tomclancys
@tomclancys
У вас почти в каждом html файле и js скрипте прописаны редиректы, отсюда и получается что много редиректов. Довольно плохая практика считаю.
Лучше весь JS код вынести в один отдельный файл и уже в нём делать все нужные проверки и соответственно редиректы.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы