登录页面HTTP请求无限发送

问题描述 投票:0回答:1

几个小时前我提出了类似的问题,但我解决了错误的问题。 真正的问题是,我有这个功能登录功能:

async function entrar() {
        const user_name = document.getElementById('user_name').value.trim();
        const password = document.getElementById('password').value.trim();

    try {
        const response = await fetch('/user/search', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `user_name=${encodeURIComponent(user_name)}&password=${encodeURIComponent(password)}`
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const objJson = await response.json();

        if (objJson && objJson.user_name === user_name && objJson.password === password) {
            localStorage.setItem('objJson', JSON.stringify(objJson));
            window.location.href = `/index?user_name=${encodeURIComponent(user_name)}&password=${encodeURIComponent(password)}`;
        } else {
            window.location.href = '/login';
        }
    } catch (error) {
        console.error('Error fetching data:', error);
        window.location.href = '/login'; // Redirect to login page on error
    }
}

它会检查我的数据库,如果我有某个用户的用户名和密码在文本框中指定,它实际上可以工作并以状态 200 响应。问题是,这个函数将我重定向到路由:“/index?user_name=某事&密码=某事”(是的,我知道它应该被编码,我会在将来处理这个问题)并且这条路线永远不会响应,它陷入“待处理”状态,就像下图所示:Network status

这是无法正常工作的路线:

app.get('/index', urlencodedParser, async function(req, res){
    let objJson = {};
    if(req.query.user_name) objJson.user_name = req.query.user_name; else objJson.user_name = false;
    if(req.query.password) objJson.password = req.query.password; else objJson.password = false;
    findUserOne(objJson, async function(result){
     if((result)&&(result.activate==true)){
         res.set('Content-Type', 'text/html');        
         const data = await fs.readFileSync('./index.html','utf8');
         await res.send(data);
     }else{
         res.set('Content-Type', 'text/html');
         const data = await fs.readFileSync('./login.html','utf8');
         await res.send(data);
     }
    });
});

我的登录字段:

<div class="container">
        <h2 align="center">LOGIN</h2>
        <br>
        <center>
            <div align="center" style="width:30%;">
                <input type="text" id="user_name" class="form-control" placeholder="Nome de usuário"><br>
                <input type="password" id="password" class="form-control" placeholder="Senha"><br>
                <br>
                <button class="btn btn-lg btn-info" onclick="entrar()">Entrar</button>
            </div>
        </center>
    </div>

javascript node.js api http node.js-fs
1个回答
0
投票

您在服务器端错误地处理了对

/index
路由的响应

更新您的后端以将其处理为

// Assuming `findUserOne` is a function that searches for a user in your database
app.get('/index', urlencodedParser, async function(req, res) {
    let objJson = {};
    if (req.query.user_name) objJson.user_name = req.query.user_name;
    if (req.query.password) objJson.password = req.query.password;

    try {
        const result = await findUserOne(objJson);

        if (result && result.activate === true) {
            const data = await fs.readFileSync('./index.html', 'utf8');
            res.set('Content-Type', 'text/html');
            res.send(data);
        } else {
            const data = await fs.readFileSync('./login.html', 'utf8');
            res.set('Content-Type', 'text/html');
            res.send(data);
        }
    } catch (error) {
        console.error('Error finding user:', error);
        res.status(500).send('Internal Server Error'); // Handle error appropriately
    }
});

并调整你的客户以理解它

async function entrar() {
    const user_name = document.getElementById('user_name').value.trim();
    const password = document.getElementById('password').value.trim();

    try {
        const response = await fetch('/user/search', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `user_name=${encodeURIComponent(user_name)}&password=${encodeURIComponent(password)}`
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const objJson = await response.json();

        if (objJson && objJson.user_name === user_name && objJson.password === password) {
            localStorage.setItem('objJson', JSON.stringify(objJson));
            window.location.href = `/index?user_name=${encodeURIComponent(user_name)}&password=${encodeURIComponent(password)}`;
        } else {
            window.location.href = '/login';
        }
    } catch (error) {
        console.error('Error fetching data:', error);
        window.location.href = '/login'; // Redirect to login page on error
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.