简体   繁体   中英

How to redirect my NodeJS app to the login page?

I've the following structure: A simple folder static , inside which I have:

index.html (the homepage that allows the user to registrate)

login.html (the login page)

In the parent folder, I've my 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')
})

The index.html page is:

<!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>

While, the login.html is:

<!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>

I simply want that after the registration (for example when in the index.html the alert is success), automatically the user is redirected to the login.html . How can I do it?

  1. from frontend:

in your 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>

instead of window.location.href = url you can also use window.location.replace(url); or window.location.assign(url)

use location.href or location.assign(url) if you want the user to be able to press back button and navigate to index.html. Use location.replace(url) if you dont want the user to be able to navigate to index.html.

Also make sure you have placed login.html in your static folder besides index.html

  1. from backenend:

Alternatively, you can also do response.redirect('/login.html') or directly send your login.html using res.send(path.join(__dirname,'static','login.html') and display the success message using frontend 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
    }   





})

Former method is simpler and complete given the information here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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