首页 > 解决方案 > 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

标签: node.jsreactjsexpress

解决方案


推荐阅读