Skip to content

[Share] Modified SignIn & API Logic for Reference and Discussion #40

Description

@bigmooon

Purpose

Sharing modified API login logic for reference.
Feel free to share feedback or suggest improvements.

Content

Fix SignIn page to properly use cookie-based login


수정된 SignIn.jsx파일

import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import AuthForm from '@/components/Auth/Authform';
import axios from 'axios';
import useAuthStore from '@/store/suho/useAuthStore';

export default function SignIn() {
  const navigate = useNavigate();
  const [loginType, setLoginType] = useState('helper');
  const setTokens = useAuthStore((state) => state.setTokens);

  const handleSubmit = async ({ email, password }) => {
    try {
      console.log(email, password);
      const response = await axios.post(
        'http://localhost:8080/api/sign/in',
        {
          userId: email,
          userPw: password,
        },
        {
          headers: {
            'Content-Type': 'application/json',
          },
          withCredentials: true,
        },
      );
      // Delete logic for accessToken
      // TODO : have to store LoginSuccess
      if (response.status === 200) {
        navigate('/');
      }
    } catch (error) {
      console.error('로그인 실패:', error);
      alert('이메일 또는 비밀번호가 올바르지 않습니다.');
    }
  };

  return (
    <>
      <div className='min-h-screen flex flex-col'>
        <main className='flex-grow '>
          <div className='container mx-auto px-4 '>
            <div className='h-[800px] flex items-center justify-center'>
              <AuthForm type={loginType} onSubmit={handleSubmit} setLoginType={setLoginType} />
            </div>
          </div>
        </main>
      </div>
    </>
  );
}

관련 api.js (src/api/index.js)

import axios from 'axios';

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true,
});

// 요청 인터셉터
api.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

export const request = async (method, endpoint, data = {}) => {
  try {
    const response = await api({
      method,
      url: `/api${endpoint}`,
      ...(method === 'GET' ? { params: data } : { data }),
    });

    console.log('API 응답: ', response);
    return response.data;
  } catch (error) {
    console.error('API 요청 오류: ', error);
    throw error;
  }
};

export default api;

Example for api

import { request } from '@/api';

export const getElderForm = async () => {
  const response = await request('GET', '/cmn/all-care-list');
  return response;
};

Notes

  • It needs to be improved more. (It's just a temporary logic for api test)
  • Discuss about token management (localStorage vs. Cookie)
  • Add login success state management(setLoginSuccess)
  • Improve error handling

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions