node.js - res.redirect 适用于 Postman,但不适用于 chrome
问题描述
该项目的目标是进行用户注册。按下提交按钮后,将触发包含电子邮件和密码的发布请求。如果找到电子邮件,则会向客户端发送 res.redirect 以重定向到失败页面。
在 chrome 控制台的 network 部分下,我们可以看到 chrome 接收到重定向响应。尽管重定向在邮递员中有效,但在 chrome 中无效。为什么?
服务器端代码如下:
app.post('/Register',async (req,res)=>{
const hashing_password = async (email, password)=>{
return new Promise((resolve,reject)=>{
bcrypt.hash(password, 10, (err,hash)=>{
if (err){
console.log('Error in hashing password')
reject(false)
}
let UserInfo = {
email: email,
hashed_password: hash,
}
console.log('hashing password sucessfully')
resolve(UserInfo)
})
})
}
const IsEmailUnique = async (UserInfo) =>{
return new Promise((resolve, reject)=>{
let FindEmailExistQuery = `SELECT * FROM users WHERE email LIKE \'${UserInfo.email}\';`
pool.query(FindEmailExistQuery, (error, results)=>{
if(error){
console.log(`Error during IsEmailUnique, and the error is ${IsEmailUnique}`)
reject(false)
}
if(results.length !== 0){
console.log(`The email already exist`)
reject(false)
}
resolve(UserInfo)
})
})
}
const AddUserToDatabase = async (UserInfo)=>{
return new Promise((resolve, reject)=>{
let AddUserToDatabaseQuery = `INSERT INTO users (email, hashed_password, register_date) values (\'${UserInfo.email}\', \'${UserInfo.hashed_password}\', now());`
pool.query(AddUserToDatabaseQuery, (error, results)=>{
if(error){
console.log(`Error during AddUserToDatabase, and the error is ${error}`)
reject(false)
}
console.log(`Add user sucessfully`)
resolve(true)
})
})
}
const RegistrationResult = await hashing_password(req.body.email, req.body.password)
.then((UserInfo)=>{
return IsEmailUnique(UserInfo)})
.then((UserInfo)=>{
return AddUserToDatabase(UserInfo)})
.catch((error)=>{
return error})
console.log(RegistrationResult)
if(!RegistrationResult){
res.redirect('https://lihkg.com/thread/2037550/page/1')
}else{
res.redirect('https://forum.hkgolden.com/channel/BW')
}
})
客户端代码如下:
import React, { useState } from 'react'
import './App.css'
import Elephant from './StockPhotos/random.jpg'
import DangerText from './DangerText/DangerText'
export default function Register() {
const [AgreeTerms, setAgreeTerms] = useState(false)
const [EmailDangerText, setEmailDangerText] = useState('none')
const [PasswordDangerText, setPasswordDangerText] = useState('none')
const [passwordReenteredDangerText, setPasswordReenteredDangerText] = useState('none')
const [AgreeTermsDangerText, setAgreeTermsDangerText] = useState('none')
let RegisterEvent = async(event) =>{
//event.preventDefault()
let EmailRegex = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g
let PasswordRegex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/gm
//- at least 8 characters
//- must contain at least 1 uppercase letter, 1 lowercase letter, and 1 number
//- Can contain special characters
let RegisterData = {
email: document.getElementById('email').value,
password: document.getElementById('password').value,
}
if(AgreeTerms === false){
setAgreeTermsDangerText('You must agree with the terms and conditions to register.')
console.log('Agree terms is false')
return false;
}
if(!EmailRegex.test(RegisterData.email)){
//event.preventDefault()
setEmailDangerText('You must enter a correct email address')
console.log('Email format is incorrect')
event.preventDefault()
return false;
}
if(!PasswordRegex.test(RegisterData.password)){
setPasswordDangerText('The password must satisfy the pattern')
console.log('password format is incorrect')
return false;
}
if(RegisterData.password != document.getElementById('passwordReentered').value){
setPasswordReenteredDangerText('The password must match')
console.log('password dont match')
return false;
}
//let RegistrationResult = await fetch('/Register',{
//method: 'POST',
//headers: {
//'Content-Type': 'application/json'
//},
//body: JSON.stringify(RegisterData)
//}).then((res)=>{
//console.log(res)
//return true
//}).catch((error)=>{
//console.log(JSON.stringify(error))
//return false
//})
fetch('/Register',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(RegisterData)
})
//console.log(result)
}
return (
<div className='d-flex flex-column vh-100 p-5 my-auto align-items-center justify-content-center'>
<img className='rounded-lg' style={{
height: '20vmin',
width: '20vmin',
}} src={Elephant}/>
<p class='font-weight-light text-center vh-10 py-3' style={{
maxHeight: '10vh',
marginBottom: 0
}}>Register here</p>
<form target="_blank">
<div className='form-group'>
<input type="email" className='form-control' placeholder='Email address' id='email' required autoFocus/>
<DangerText DangerText={EmailDangerText}/>
</div>
<div className='form-group'>
<input type="password" className='form-control' placeholder='Password' id='password' required autoFocus/>
<DangerText DangerText={PasswordDangerText}/>
<small id="emailHelp" class="form-text text-muted">The password must match the following pattern:
<br/>- at least 8 characters
<br/>- must contain at least 1 uppercase letter, 1 lowercase letter, and 1 number
<br/>- Can contain special characters
</small>
</div>
<div className='form-group'>
<input type="password" className='form-control' placeholder='Reenter your password' id='passwordReentered' required autoFocus/>
<DangerText DangerText={passwordReenteredDangerText}/>
</div>
<div class="form-group form-check text-center">
<input type="checkbox" class="form-check-input" onClick={()=>{setAgreeTerms(!AgreeTerms)}} autoFocus required/>
<label class="form-check-label" for="AgreeTerms">I agree with the terms and conditions</label>
<DangerText DangerText={AgreeTermsDangerText}/>
</div>
<button type="submit" className="btn btn-primary d-flex mx-auto" onClick={(event)=>{RegisterEvent(event)}}>Register</button>
</form>
</div>
)
}
github存储库如下: https ://github.com/1564851/Qaudcopter-delivery-website-by-MySQL-and-React
解决方案
推荐阅读
- reactjs - 为什么子状态值第一次没有在父回调函数中更新?
- python - Numba 无法编译并显示非常奇怪的消息 - 似乎这应该有效?
- mysql - 数据库查询将是什么?
- swift - SwiftUI 将保存的值传递给父视图
- html - 添加到徽标的链接会添加到整个导航栏的链接
- postgresql - Liquibase 忽略数据库内容并从头开始创建差异
- swift - how to use form data in Alamofire
- php - 用 preg_replace 替换确切的域
- javascript - 检测 Alt/Option + textarea 中的另一个键
- python - Spyne(python web 服务框架)是否支持多线程?如果没有,有没有办法使用 Python 线程库?