MetalRoze / OnlineNews_FE

2 stars 1 forks source link

[feat] axios api #100

Open eunznidang opened 1 week ago

eunznidang commented 1 week ago

๐Ÿ’ฅ axios get, post, delete, patch ๋งŒ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค ..

1. ํ† ํฐ ์„ค์ • (๋กœ๊ทธ์ธ api ์—ฐ๊ฒฐ ์ „๊นŒ์ง„ ์ด๋ ‡๊ฒŒ ์„ค์ •ํ•ด์•ผ ํ•จ)

ํฌ๋กฌ f12 -> application -> session storage์˜ localhost์— ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ถ”๊ฐ€ @dahxxn ์ œ๊ฐ€ ๋กœ๊ทธ์ธ api ๋ถˆ๋Ÿฌ์™€์„œ ํ† ํฐ ์„ค์ •๊นŒ์ง„ ํ•ด๋’€์œผ๋‹ˆ, ๋ฆฌํ”„๋ ˆ์‹œํ† ํฐ ๋ฐ ์ดํ›„ ๋กœ์ง ์งœ์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค ~

image

2. ์‚ฌ์šฉํ•  ์ปดํฌ๋„ŒํŠธ์—์„œ ..

  1. ์‚ฌ์šฉํ•  ํ•จ์ˆ˜ import import { getRequest } from './apiClient ๊ฒฝ๋กœ'; : params ๋ณด๋‚ผ ์ˆ˜ ์žˆ๋Š” get import { postRequest } from './apiClient ๊ฒฝ๋กœ'; : body ๋ณด๋‚ผ ์ˆ˜ ์žˆ๋Š” post import { putRequest } from './apiClient ๊ฒฝ๋กœ'; import { patchRequest } from './apiClient ๊ฒฝ๋กœ'; import { deleteRequest } from './apiClient ๊ฒฝ๋กœ';

  2. ์ด๋Ÿฐ์‹์œผ๋กœ ์š”์ฒญํ•˜๋ฉด ๋จ. ๋งŒ๋“ค์–ด๋‘” ํ•จ์ˆ˜ ์™ธ์— ์ปค์Šคํ…€ํ•ด์„œ ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ์œผ๋ฉด apiClient์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ ํ•จ์ˆ˜ ์ถ”๊ฐ€๋กœ ๋งŒ๋“ค์–ด์„œ ์‚ฌ์šฉํ•˜์„ธ์š”

    const fetchArticle = async () => {
        try { 
          const response = await getRequest('/api/article/select', { id: articleId }); 
        } catch (error) {
          setError('๊ธฐ์‚ฌ ์ •๋ณด๋ฅผ ๋ถˆ๋Ÿฌ์˜ค๋Š” ๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.');
        } 
    };
       const data={
            email: email,
            password: password
        }

        postRequest('/api/user/login', data)
            .then(response => {
                console.log(response.data);
                sessionStorage.setItem('authToken', response.data.accessToken);
                console.log('์ €์žฅ๋œ authToken:', sessionStorage.getItem('authToken'));
            })
            .catch(error => {
                console.error('Error fetching subscriptions:', error);
            });
dahxxn commented 1 week ago

ํ—ค๋”์— ํ† ํฐ ์—†์ด ์‚ฌ์šฉํ•  apiClient ๋งŒ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค (../../apis/noTokenAxios.jsx)

const noTokenFormDataApiClient = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
});

// ์•„๋ž˜๋Š” formData๋ฅผ ๋„˜๊ธฐ๋Š” ํ•จ์ˆ˜ 
// POST ์š”์ฒญ 
const postRequest = (url, formData) => {
    return noTokenFormDataApiClient.post(url, formData)
        .then(response => response) 
        .catch(error => {
            console.error('POST ์š”์ฒญ ์˜ค๋ฅ˜:', error);
            throw error;
        });
};