로그인 정보를 입력하면 가입할 수 없습니다.
10174 단어 axiosjavascriptnodereact
아래 코드도 도움이 될 것입니다!
구성 요소 폴더의 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;
도움이 될 것입니다. 대단히 감사합니다 !!!
Reference
이 문제에 관하여(로그인 정보를 입력하면 가입할 수 없습니다.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/jtcodes_/unable-to-sign-up-once-log-in-details-have-been-entered-5c7l텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)