繁体   English   中英

如何将我的 NodeJS 应用程序重定向到登录页面?

[英]How to redirect my NodeJS app to the login page?

我有以下结构:一个简单的文件夹static ,里面有:

index.html (允许用户注册的主页)

login.html (登录页面)

在父文件夹中,我有我的server.js

const express = require('express')
const path = require('path')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
const bcrypt = require('bcryptjs')
const User = require('./model/user')
const jwt = require('jsonwebtoken')


mongoose.connect('mongodb://localhost:27017/bank-db', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    //useCreateIndex: true
})

const JWT_SECRET = 'jhhgf122aweòg€@wthmioqa_sadof'

const app = express()
app.use('/', express.static(path.join(__dirname, 'static')))
app.use(bodyParser.json())


app.post('/api/register', async(req,res) =>{

    const { username, email, password: plainTextPassword  } = req.body



    if(!username || typeof(username) !== 'string'){
        return res.json({status: "error", error: "Invalid Username. Please, retry."})
    }

    if(!plainTextPassword || plainTextPassword.length < 6 ){
        console.log(plainTextPassword.lenght)
        return res.json({status: "error", error: "Invalid Password. Minium Length is 6 characters. Please, retry"})
    }

    if(!email || !email.includes("@")){
        return res.json({status: "error", error: "Invalid Email. At least it should contain @."})
    }
    const password = await bcrypt.hash(plainTextPassword, 10)

    try {
        const response = await User.create({
            username,
            email,
            password
        })
        console.log('User created successfully: ', response)
        res.json({status : "ok"})

    } catch (error) {
        if (error.code === 11000) {

            return res.json({ status: 'error', error: 'Username or email already in use' })
        }
        throw error
    }   





})

app.post('/api/login', async (req, res) => {
    const { username, password } = req.body
    const user = await User.findOne({ username }).lean()

    if (!user) {
        return res.json({ status: 'error', error: 'Invalid username or password. Please, retry.' })
    }

    if (await bcrypt.compare(password, user.password)) {

        const token = jwt.sign(
            {
                id: user._id,
                username: user.username
            },
            JWT_SECRET
        )

        return res.json({ status: 'ok', data: token })
    }

    res.json({ status: 'error', error: 'Invalid username/password' })
})

app.listen(3000, () => {
    console.log('SERVER ON PORT 3000')
})

index.html页面是:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <h1>Registration</h1>
        <form id="reg-form">
            <input type="text" autocomplete="off" id="username" placeholder="Username" />
            <input type="password" autocomplete="off" id="password" placeholder="Password" />
            <input type="submit" value="Submit Form" />
        </form>

        <script>
            const form = document.getElementById('reg-form')
            form.addEventListener('submit', registerUser)

            async function registerUser(event) {
                event.preventDefault()
                const username = document.getElementById('username').value
                const password = document.getElementById('password').value
                const password = document.getElementById('email').value

                const result = await fetch('/api/register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username,
                        email,
                        password
                    })
                }).then((res) => res.json())

                if (result.status === 'ok') {
                    // everythign went fine
                    alert('Success')
                } else {
                    alert(result.error)
                }
            }
        </script>
    </body>
</html>

login.html是:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Login</title>
    </head>
    <body>
        <h1>Login</h1>
        <form id="login">
            <input type="text" autocomplete="off" id="username" placeholder="Username" />
            <input type="password" autocomplete="off" id="password" placeholder="Password" />
            <input type="submit" value="Submit Form" />
        </form>

        <script>
            const form = document.getElementById('login')
            form.addEventListener('submit', login)

            async function login(event) {
                event.preventDefault()
                const username = document.getElementById('username').value
                const password = document.getElementById('password').value

                const result = await fetch('/api/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username,
                        password
                    })
                }).then((res) => res.json())

                if (result.status === 'ok') {
                    // everythign went fine
                    console.log('Got the token: ', result.data)
                    localStorage.setItem('token', result.data)
                    alert('Success')
                } else {
                    alert(result.error)
                }
            }
        </script>
    </body>
</html>

我只是希望在注册后(例如当在index.html中警报成功时),自动将用户重定向到login.html 我该怎么做?

  1. 从前端:

在你的 index.html

<script>
            const form = document.getElementById('reg-form')
            .
            .
            .
            .
            .
            .
            .
            .
                }).then((res) => res.json())

                if (result.status === 'ok') {
                    // everythign went fine
                    window.location.href = baseUrl+'/login.html'//add this line to redirect
                    alert('Success')
                } else {
                    alert(result.error)
                }
            }
        </script>

而不是window.location.href = url你也可以使用window.location.replace(url); window.location.assign(url)

如果您希望用户能够按下后退按钮并导航到 index.html,请使用location.hreflocation.assign(url) 如果您不希望用户能够导航到 index.html,请使用location.replace(url)

还要确保除了 index.html 之外,您已将 login.html 放在 static 文件夹中

  1. 从后端:

或者,您也可以执行response.redirect('/login.html')或使用res.send(path.join(__dirname,'static','login.html')直接发送您的 login.html 并显示成功消息使用前端js。

app.post('/api/register', async(req,res) =>{

    const { username, email, password: plainTextPassword  } = req.body
    .
    .
    .
    .
    .
    .
        console.log('User created successfully: ', response)
        // res.json({status : "ok"})
        // redirect using response.redirect('/login.html')` or directly send your login.html using res.send(path.join(__dirname,'static','login.html')
        // display success message on login.html using frontend js code

    } catch (error) {
        if (error.code === 11000) {

            return res.json({ status: 'error', error: 'Username or email already in use' })
        }
        throw error
    }   





})

鉴于此处的信息,前一种方法更简单、更完整

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM