로그인 정보를 입력하면 가입할 수 없습니다.

안녕하세요 여러분, react.js를 처음 접하는 저는 채팅 애플리케이션을 구축하려고 합니다. 안타깝게도 가입 버튼을 눌렀을 때 경로가 없고 다음 페이지로 들어갈 수 없는 문제가 발생했습니다. 아래는 내가보고있는 오류의 사진입니다.



아래 코드도 도움이 될 것입니다!
구성 요소 폴더의 index.js 파일(클라이언트 측)

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 파일(클라이언트 측)


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 파일(서버 측)


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 }




route 폴더의 Auth.js 파일(서버 측)

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;




도움이 될 것입니다. 대단히 감사합니다 !!!

좋은 웹페이지 즐겨찾기