Unable to sign up once log in details have been entered
Tags: node, javascript, react, axios
Published: 2022-09-21 17:13:35


Hello guys , im new to react.js an im attemting to build a chat application. Unfortunately i've ran into a problem whereby when i press the sign up button there seems to me no route and i cant enter the next page. Below is a picture of the error im seeing:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z8n5vn6cmmvkjkocm61q.png)


The codes below should help aswell !
index.js file in components folder (client side)
````
const express = require ('express');
const cors = require ('cors');

//adding routes for sign in + registrationn//
const authRoutes = require("./routes/auth.js");

const app = express ();
const PORT = process.env.PORT || 5009;

require ('dotenv').config();

app.use(cors());
app.use(express.json());
app.use(express.urlencoded());

app.get('/' , (req,res) => {
     res.send('ne, world');

});

app.use('/auth', authRoutes);

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

```

Auth.jsx file in components folder (client side )
```

import React, {useState} from 'react';
import Cookies from 'universal-cookie';
import axios from 'axios';

import signinImage from '../assets/Group 2.png';

const cookies = new Cookies();


//forming the inital state of input fields 
const initialState = {
   fullName:'',
   username:'',
   password:'',
   confirmPassword:'',
   phoneNumber:'',
   avatarURL:'',

  
}
const Auth = () => {

    const [form, setForm] = useState(initialState);

    const [isSignup , setIsSignup] = useState(true);

    const handleChange = (e) => {

        setForm({...form,[e.target.name]: e.target.value});

    }

    const handleSubmit = async  (e)=>{
       e.preventDefault();

       const {username , password , phoneNumber , avatarURL } = form;

       const URL = 'http://localhost:5009/auth/SignUp'
       
       //making requests to different url backened each time 
       const {data :  { token ,userId , hashedPassword , fullName }} = await axios.post(`${URL}/${isSignup ? 'Sign Up ' : 'Sign In'}`,{
         username , password , fullName: form.fullName , phoneNumber , avatarURL,
       })
       //storing data in cookies 
       cookies.set('token ' , token )
       cookies.set('username ' , username )
       cookies.set('fullName' , fullName)
       cookies.set('userId ' , userId )

       if (isSignup){
         cookies.set('phoneNumber' , phoneNumber )
         cookies.set('avatarURL' , avatarURL)
         cookies.set('hashedPassword' , hashedPassword )
       }
       //reloads application
       window.location.reload();
    }
    //changing state of my sign up screen depending on the state before
    const switchMode = () => {
      setIsSignup((prevIsSignup) => !prevIsSignup);
  }



  return (
    <div className=" auth__form-container">
        <div className="auth__form-container_fields">
            <div className="auth__form-container_fields-content">
                <p>{isSignup ? 'Sign up' : 'Sign In'}</p>
                <form onSubmit= {handleSubmit}>
                 {isSignup &&(
                     <div className= "auth__form-container_fields-content_input">
                        <label htmlFor="fullName">Full Name</label>
                        <input
                         name="fullName"
                         type="text"
                         placeHolder= "Full Name"
                         onChange={handleChange}
                         required
                        />
                     </div>
                 ) }
                  <div className= "auth__form-container_fields-content_input">
                        <label htmlFor="username">Username</label>
                        <input
                         name="username"
                         type="text"
                         placeHolder= "Username"
                         onChange={handleChange}
                         required
                        />
                     </div>
                     {isSignup &&(
                     <div className= "auth__form-container_fields-content_input">
                        <label htmlFor="phoneNumber">Phone Number</label>
                        <input
                         name="phoneNumber"
                         type="text"
                         placeHolder= "Phone Number"
                         onChange={handleChange}
                         required
                        />
                     </div>
                 ) }
                 {isSignup &&(
                     <div className= "auth__form-container_fields-content_input">
                        <label htmlFor="avatarURL">Avatar URL</label>
                        <input
                         name="avatarURL"
                         type="text"
                         placeHolder= "Avatar URL"
                         onChange={handleChange}
                         required
                        />
                     </div>
                 ) }
                 <div className= "auth__form-container_fields-content_input">
                        <label htmlFor="password">Password</label>
                        <input
                         name="password"
                         type="password"
                         placeHolder= "Password"
                         onChange={handleChange}
                         required
                        />
                     </div>
                     {isSignup &&(
                     <div className= "auth__form-container_fields-content_input">
                        <label htmlFor="confirmPassword">Confirm Password</label>
                        <input
                         name="confirmPassword"
                         type="password"
                         placeHolder= "Confirm Password"
                         onChange={handleChange}
                         required
                        />
                     </div>
                 ) }
                     
                   <div className="auth__form-container_fields-content_button">
                    <button>{isSignup ? "Sign up " : "Sign In"}</button>
                    </div>  
                </form>
              <div className="auth__form-container_fields-account">
                <p>
                    {isSignup 
                    ? "Already have an account?"
                    :"Dont have an account ?"
                 }
                 <span onClick={switchMode}>
                    {isSignup ? ' Sign In' : ' Sign up'}

                 </span>
                </p>

              </div>
            </div>

        </div>

      <div className="auth__form-container_image">
        <img src = {signinImage} alt ="Sign In" />

      </div>
    </div>
  )
}

export default Auth


```
Auth.js file in controller folder (server side )
```

const { connect } = require('getstream');
const bcrypt = require('bcrypt');
const StreamChat = require('stream-chat').StreamChat;
const crypto = require('crypto');

require('dotenv').config();

const api_key = process.env.STREAM_API_KEY;
const api_secret = process.env.STREAM_API_SECRET;
const app_id = process.env.STREAM_APP_ID;

const signup = async (req, res) => {
    try {
        const { fullName, username, password, phoneNumber } = req.body;

        const userId = crypto.randomBytes(16).toString('hex');

        const serverClient = connect(api_key, api_secret, app_id);

        const hashedPassword = await bcrypt.hash(password, 10);

        const token = serverClient.createUserToken(userId);

        res.status(200).json({ token, fullName, username, userId, hashedPassword, phoneNumber });
    } catch (error) {
        console.log(error);

        res.status(500).json({ message: error });
    }
};

const login = async (req, res) => {
    try {
        const { username, password } = req.body;
        
        const serverClient = connect(api_key, api_secret, app_id);
        const client = StreamChat.getInstance(api_key, api_secret);

        const { users } = await client.queryUsers({ name: username });

        if(!users.length) return res.status(400).json({ message: 'User not found' });

        const success = await bcrypt.compare(password, users[0].hashedPassword);

        const token = serverClient.createUserToken(users[0].id);

        if(success) {
            res.status(200).json({ token, fullName: users[0].fullName, username, userId: users[0].id});
        } else {
            res.status(500).json({ message: 'Incorrect password' });
        }
    } catch (error) {ads
        console.log(error);

        res.status(500).json({ message: error });
    }
};

module.exports = { signup, login }


```
Auth.js file in routes folder (server side)
```
const express = require ('express');

const { signup, login } = require('../controllers/auth.js/');

const router = express.Router();

//initialising my 2 different routes //
//post route sending data from frontend to backend 
router.post('/signup', signup);
router.post('/login', login);


module.exports = router;


```

Any help would be , much appreciated thank you !!!