2024.02.26 TIL

Oneik·2024년 2월 26일
0
post-thumbnail

라우트 작성

ReactRouter 설치 방법

npm install react-router-dom @types/react-router-dom --save

ReactRouter 사용 방법

  1. createBrowserRouter를 이용하여 router를 만든다
    • 클라이언트가 어떠한 경로로 접근했을 때, 보여줄 컴포넌트를 설정한다
  2. RouterProvider를 이용하여 Router 인스턴스를 제공한다
const router = createBrowserRouter([
	{
		path: '/',
		element: (
			<Layout>
				<Home />
			</Layout>
		),
		errorElement: <Error />,
	},
	{
		path: '/books',
		element: <div>도서 목록</div>,
	},
]);

function App() {
	return (
		<BookStoreThemeProvider>
			<RouterProvider router={router} />
		</BookStoreThemeProvider>
	);
}

Axios

브라우저와 Node.js에서 사용할 수 있는 Promise 기반 HTTP 클라이언트

HTTP 클라이언트
웹 서버와 통신하기 위해 HTTP 요청을 생성하고 보내는 소프트웨어나 라이브러리
인터넷을 통해 제공되는 리소스(자원)을 요청하고 그 결과를 받아올 수 있다

특징

  • 브라우저를 위해 XMLHttpRequests 생성
    - XHR을 사용하면 페이지의 새로고침 없이도 URL에서 데이터를 가져올 수 있다
  • node.js를 위해 http 요청 생성
  • Promise API 지원
  • 요청 및 응답 인터셉트
  • 요청 및 응답 데이터 변환
  • 요청 취소
  • JSON 데이터 자동 변환
  • XSRF를 막기 위한 클라이언트 사이드 지원

Axios 인스턴스

사용자 지정 config로 새로운 Axios 인스턴스를 만들 수 있다

axios.create([config])

const createInstance = (config?: AxiosRequestConfig) => {
	const axiosInstance = axios.create({
		baseURL: 'http://localhost:9999',
		timeout: 30000,
		header: {
			'Content-Type': 'application/json'
		},
		withCredentials: true, // 자격 증명 사용, 사이트 간 액세스 제어 요청을 해야하는지 여부
		...config,
	})
}

인터셉터

then 또는 catch 로 처리되기 전에 요청과 응답을 가로챌 수 있다

// 요청 인터셉터 추가
axios.intercepters.request.use(
	function (config) {
		// 요청이 전달되기 전에 작업 수행
		return config;
	}, function (error) {
	// 요청 오류가 있는 작업 수행
		return Promise.reject(error);
	}
);

// 응답 인터셉터 추가
axios.intercepters.response.use(
	function (response) {
		// 2xx 범위에 있는 상태 코드일 경우, 이 함수를 트리거 한다
		// 응답 데이터가 있는 작업 수행
		return response;
	}, function (error) {
		// 2xx 외의 범위에 있는 상태 코드는 이 함수를 트리거 한다
		// 응답 오류가 있는 작업 수행
		return Promise.reject(error);
	}
);

RouterProvider

  • RouterProvider는 경로를 컴포넌트와 연결하기 위해 필요한 기능들을 제공한다. Layout 안에 Link와 같은 기능들이 존재함으로, Layout은 RouterProvider 하위에 작성되어 있어야한다.
    그러나, Layout이 RouterProvider를 감싸고 있는 형태였음으로 아래와 같은 에러가 발생했다
Cannot destructure property 'basename' of 'react__WEBPACK_IMPORTED_MODULE_0__.useContext(...)' as it is null. TypeError: Cannot destructure property 'basename' of 'react__WEBPACK_IMPORTED_MODULE_0__.useContext(...)' as it is null. at LinkWithRef (http://localhost:3000/static/js/bundle.js:38874:5) at renderWithHooks (http://localhost:3000/static/js/bundle.js:25731:22) at updateForwardRef (http://localhost:3000/static/js/bundle.js:28300:24) at beginWork (http://localhost:3000/static/js/bundle.js:30347:20) at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:15327:18) at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:15371:20) at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:15428:35) at beginWork$1 (http://localhost:3000/static/js/bundle.js:35292:11) at performUnitOfWork (http://localhost:3000/static/js/bundle.js:34540:16) at workLoopSync (http://localhost:3000/static/js/bundle.js:34463:9)
profile
초보 개발자의 블로그입니다

0개의 댓글

관련 채용 정보