프로젝트 일지

[🐾일지] Axios Network Error (Failed to load resource: net::ERR_CONNECTION_REFUSED)

Kamea 2022. 5. 15. 18:34

아름다워...딸기와 망고의 조화

 

프로젝트 서버 연결할 때 무조건 한 번은 눈에 보이는 에러다. 에러 주저리가 너무 길어서 읽을 염두도 안 나는... 그런 에러다.

 

👇🏻 에러 풀 소개

Access to XMLHttpRequest at 'http://localhost:3000/api/user/login' from origin 'http://localhost:5000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

 

대충 XMLHttpRequest와 서버, 클라이언트의 포트 주소가 나오는 것을 보니 아...데이터 송신에 문제가 있군... 이렇게 생각이 든다.

 

내가 지금 하고 있는 프로젝트의 포트 주소는 아래와 같다.

클라이언트 👉🏻 http://localhost:5000

서버 👉🏻 http://localhost:3000

 

CORS 정책에 따라 클라이언트 포트가 서버에 접근하는게 막혔다. 이런 문제가 나타나서 접근 권한을 부여해주어야 한다.

인터넷에 많이 나오는 방법은 크게 2가지이다.

 

1. 클라이언트에서 해결 : 실패

axios.defaults. withCredentials = true; 설정 & 전달 header에 {withCredentials:true,} 를 포함할 것

 

내가 해봤는데 계속 같은 에러가 나타난다. 

 

 

2. 서버에서 해결 : 성공

 

// 서버 코드
const cors = require('cors')

app.use(cors({ credentials: true, origin: "http://localhost:5000" }));

 

서버 코드를 위와 같이 변경해주면 된다. (나는 원래는 app.use(cors());로 되어 있었다.)

 

/* 클라이언트 코드 */
await API.post('/user/login', userData, {
            withCredentials: true,
        })
            .then((res) => {
                console.log('>>> [LOGIN] ✅ SUCCESS', res.data.email);
                if (res.status === 200) {
                    navigate('/home');
                }
            })
            .catch((err) => {
                console.warn('>>> [LOGIN] 🤬 ERROR', err.message);
                ...);
    };

 

 

해결~~

 

끝 !