codestates / codestates/Touch

[Error handling] uncaught (in promise) error: request failed with status code 401

Open
#50 0 comments 0 reactions 0 assignees View on GitHub
Complete error
Dominant language
JavaScript
Stars
0
Forks
1
PR merge metrics
No merged PRs in 30d

Description

> ### 어떤 에러인가요?
> 로그아웃 기능 구현 시 axios 요청 보낼 때 쿠키카 요청 헤더에 담기지 않았던 문제.
>
> ### 에러 메시지
> ```shell
> uncaught (in promise) error: request failed with status code 401
> ```
>
> ### 에러 핸들링 방법
> axios를 사용해서 get 요청이나 post 요청을 보낼때 함수안에 데이터가 들어가는 자리나 config가 들어가는 자리가 다르다보니 { withCredentials: true } 옵션을 줘도 post 요청 시 잘 작동되지 않았던 문제였습니다.
> 간단히 말하자면 get 요청시에는 axios.get('주소', {config}) 첫번째 인자로 주소, 두번째 인자로 config가 들어갔으나
> post 요청시에는 axios.post('주소', {데이터}, {config}) 첫번째 인자로 주소, 두번째 인자로 보내는 데이터, 세번째 인자로 config가 들어가야 합니다. 아래에 좀 더 자세한 설명이 있습니다.
>
> ```js
> const handleLogout = () => {
> axios
> .post('https://localhost:4000/logout',
> {},
> { withCredentials: true })
> .then(() => {
> setUserinfo(null);
> setIsLogin(false);
> history.push('/');
> });
> };
> ```
>
> 위 코드에서처럼, 두번째 인자, 데이터가 들어갈 자리에 보내줄 데이터가 없다고 하면 저렇게 빈 객체라도 넣어줘야 합니다.
> 보내줄 데이터가 없다고 데이터가 들어갈 자리에 { withCredentials: true } 옵션을 설정해주면 요청시 그것을 데이터로 인식해 사실상 { withCredentials: true } 옵션 없이 요청을 보내는것이나 마찬가지였습니다. 그래서 위와같이 각자의 자리에 맞는 설정을 해주고 요청을 보내니 문제없이 잘 작동했습니다.
>
> ### 에러 핸들링을 위해 참고한 레퍼런스 링크
> [링크](https://velog.io/@bigbrothershin/Backend-Axios-%EC%82%AC%EC%9A%A9-%EC%8B%9C-%EC%A3%BC%EC%9D%98%EC%82%AC%ED%95%AD)

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.