0

The goal of the project is to have user registration. Once the submit button is pressed, a post request containing the email and password is fired. If the email is found, a res.redirect is send to the client to redirect to the failure page.

Under the network section in chrome console, we can find the chrome receive the redirect response. Although the redirect works in postman, it does not work in chrome. Why?

enter image description here

The server side code is the following:

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')
    }
})

The client side of code is the followng:

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>
    )
}

The github repository is the following: https://github.com/1564851/Qaudcopter-delivery-website-by-MySQL-and-React

Jordan Ho
  • 11
  • 1
  • 1
  • Ajax calls from the browser do not cause the browser to change pages when they receive a redirect. The Ajax call just delivers a 302 response to your Javascript and it's up to your Javascript to decide what to do about it. See the questions yours has been marked a duplicate of for more info. – jfriend00 May 29 '20 at 04:25
  • Other references: [Redirect page after post request in Express](https://stackoverflow.com/questions/38449568/redirect-page-after-post-request-express-4/38449699#38449699), [What is the difference between POST api call and POST browser form submission](https://stackoverflow.com/questions/58230804/what-is-the-difference-between-post-api-call-and-form-submission-with-post-metho/58230870#58230870), [Page does not redirect](https://stackoverflow.com/questions/56553845/my-express-js-and-passport-js-middleware-are-all-working-and-are-being-called-b/56554261#56554261). – jfriend00 May 29 '20 at 04:28

0 Answers0