html 使用按钮和node.js重定向页面

fykwrbwg  于 2023-03-06  发布在  Node.js
关注(0)|答案(1)|浏览(150)

我有两个HTML文件:

  • index.html,这是登录页面
  • register.html

在Node.js中,我使用getpost方法来操作。注册页面是为/register操作设置的,并且包含在标记中。我对Node.js还比较陌生,所以不太明白哪里出了问题。下面是我的节点代码(改为使用express):

const express = require('express')
const bodyParser = require('body-parser')
const path = require('path')

const app = express()

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use('/css', express.static(path.join(__dirname, 'css')));
app.use('/img', express.static(path.join(__dirname, 'img')));
app.use('/jS', express.static(path.join(__dirname, 'jS')));

// Serve the HTML file
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'html', 'index.html'));
});

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'html', 'registerForm.html'));
});

app.post('/login', (req, res) => {
    const fs = require('fs');
    fs.readFile('login.json', 'utf8', (err, data) => {
        if (err) {
            console.log(err)
        } else {
            const username = req.body.username;
            const password = req.body.password;
            const users = JSON.parse(data);
            let user = users[username];
            if (user) {
                if (user.password === password) {
                    res.writeHead(200, {'Content-Type': 'text/html'});
                    res.write('User logged in');
                    return res.redirect('/mx5');
                } else {
                    res.writeHead(200, {'Content-Type': 'text/html'});
                    res.write('Password incorrect');
                    res.end();
                }
            } else {
                res.writeHead(200, {'Content-Type': 'text/html'});
                res.write('User does not exist');
                return res.redirect('register');
            }
        }
    });
})

app.post('/register', (req, res) => {
    const fs = require('fs');
    fs.readFile('login.json', 'utf8', (err, data) => {
        if (err) {
            console.log(err)
        } else {
            let users = JSON.parse(data);
            const username = req.body.username;
            const password = req.body.password;
            const rpassword = req.body.rpassword;
            // Check if user already exists in JSON file
            const user = users[username];
            if (user) {
                res.writeHead(200, {'Content-Type': 'text/html'});
                res.write('Username already in use');
            } else {
                while (password !== rpassword) {
                    res.writeHead(200, {'Content-Type': 'text/html'});
                    res.write('Passwords not corresponding')
                }
                // Add new user to JSON file
                user.password = password;
                fs.writeFileSync('users.json', JSON.stringify(users));
                res.writeHead(200, {'Content-Type': 'text/html'});
                res.write('User added');
                return res.redirect('/mx5');
            }
        }
    });
})

app.listen(3000, () => {
    console.log('Server running at http://localhost:3000/')
})

我的两个HTML文件:

    • 索引. html**
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dynamic Website</title>
    <link rel="stylesheet" type="text/css" href="../css/styleSheet.css">
</head>
<body>
<header class="welcome">Welcome</header>
<p id="current-time" class="time"></p>
<div class="login-container">
    <form method="POST" action="/login">
        <h1>Login</h1>
        <label for="username">Username:</label>
        <input type="text" id="username" name="username">
        <label for="password">Password:</label>
        <input type="password" id="password" name="password">
        <label for="show-password">Show Password</label>
        <input type="checkbox" id="show-password" onclick="togglePassword()" class="show-password">
        <button type="submit">Submit</button>
        <button type="button" onclick="window.location.href='/register';" id="register-button">Register here</button>
    </form>
</div>
<script src="../jS2.js"></script>
</body>
</html>
    • 注册表. html**
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Register Form</title>
    <link rel="stylesheet" type="text/css" href="../css/registerStyle.css">
</head>
<body>
<div class="register-container">
    <form method="POST" action="/register">
        <h1>Register</h1>
        <label for="firstName">First name:</label>
        <input type="text" id="firstName" name="firstName" pattern="^\p{L}[-_]\p{L}$.{,20}" required>
        <label for="lastName">Last name:</label>
        <input type="text" id="lastName" name="lastName" pattern="^\p{L}[-_]\p{L}$.{,20}" required>
        <label for="male">Male</label>
        <input type="radio" id="male" name="gender" checked>
        <label for="female">Female</label>
        <input type="radio" id="female" name="gender">
        <label>Check interests:</label>
        <fieldset>
            <legend>Select your interests:</legend>
            <label for="mx5">MX5</label>
            <input type="checkbox" id="mx5" name="MX5" class="mx5">
            <label for="rx7">RX7</label>
            <input type="checkbox" id="rx7" name="RX7" class="rx7">
            <label for="skyline">Skyline</label>
            <input type="checkbox" id="skyline" name="Skyline" class="skyline">
        </fieldset>
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password"
               pattern="^(?=.*[0-9])(?=.*[!#,+\-_?])(?=.{8,})\S+$"
               title="Password must contain at least one uppercase, one lower case letter, a number, one of the following characters !#,+-_? and must have a length of 8-20 characters."
               required>
        <label for="show-password">Show Password</label>
        <input type="checkbox" id="show-password" onclick="togglePassword()" class="show-password">
        <label for="rpassword">Confirm Password:</label>
        <input type="password" id="rpassword" name="rpassword" required>
        <label for="comment">Leave a Comment:</label>
        <textarea id="comment" name="comment" maxlength="100"></textarea>
        <label for="agree">Agree with the user terms</label>
        <input type="checkbox" id="agree" name="agree" required>
        <button type="submit" onclick="redirect()">Register</button>
    </form>
</div>
<script src="../jS2.js"></script>
</body>
</html>

基本上,我希望在登录页面上,它在登录时重定向到mx5页面,在单击注册按钮时重定向到注册页面,但我不能让它与node.js一起工作,本地将没有问题。

jv2fixgn

jv2fixgn1#

我让它工作了,问题是使用方法post而不是get in the forms。

相关问题