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



我有以下结构:一个简单的文件夹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. from frontend:

你的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.replace(url);window.location.assign(url)来代替window.location.href = url

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

除了index.html

之外,还要确保在静态文件夹中放置了login.html
  1. from backenend:

或者,你也可以使用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
}   


})

前一种方法更简单,更完整,因为这里有

的信息

相关内容

最新更新