[React] AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK'…}

지쥬·2025년 1월 23일
0

React

목록 보기
1/1
post-thumbnail

react로 프론트를 구현하고 spring boot로 백을 구현해서 api로 둘을 연결하기로 했다. 나는 프론트를 맡았고, 다른 컴퓨터로 백을 구현한 상태, 나는 백과 프론트를 연결해본 경험이 처음이였기에 gpt의 힘을 빌려 연결 시작

const api = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
  }
});

이런식으로 axios 연결하고

const handleSearch = async (e) => {
  const barcodePackage = e.target.value;
  setSearchQuery(barcodePackage);

  if (barcodePackage) {
    try {
      const response = await api.get(`/api/products/barcode/${barcodePackage}`);
      setFormData(response.data);
    } catch (error) {
      console.error("Error details:", error.response || error);
      alert('제품을 찾을 수 없습니다.');
    }
  }
};

const handleSubmit = async (e) => {
  e.preventDefault();
  try {
    const response = await api.patch(`/api/products/${formData.id}`, formData);
    alert('제품 정보가 업데이트되었습니다!');
    console.log('Updated Data:', response.data);
  } catch (error) {
    console.error('Error details:', error.response || error);
    alert('업데이트 중 오류가 발생했습니다.');
  }
};

검색과, 제출 함수도 수정했다. api get 사용해서 spring boot랑 url을 맞게 설정하면 된다길래 드디어 백 프론트 연결을 해본다는 기쁜 마음으로 npm run dev 을 했지만

  1. AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
    1. code: "ERR_NETWORK"
    2. config: {transitional: {…}, adapter: Array(3), transformRequest: Array(1), transformResponse: Array(1), timeout: 5000, …}
    3. message: "Network Error"
    4. name: "AxiosError"
    5. request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 5000, withCredentials: false, upload: XMLHttpRequestUpload, …}
    6. stack: "AxiosError: Network Error\n at XMLHttpRequest.handleError (http://localhost:5173/node_modules/.vite/deps/axios.js?v=a5c51f36:1596:14)\n at Axios.request (http://localhost:5173/node_modules/.vite/deps/axios.js?v=a5c51f36:2124:41)\n at async handleSearch (http://localhost:5173/src/components/updatePage.jsx:60:26)"
    7. [[Prototype]]: Error
      updatePage.jsx:140 GET http://localhost:8080/api/products/barcode/8809750463767 net::ERR_CONNECTION_REFUSED

ㅇ ㅖ... 에러 발생..⭐️

1시간을 해결하지 못하고 react 코드, spring boot 코드 둘 다 열심히 수정해보았지만 계속계속 발생하는

AxiosError

도대체 뭐가 문제인건지 모르겠어서 둘이 머리 싸매고 고민했다ㅠㅠ

해결 방법으로
1. 백엔드 서버가 8080 포트에서 실행 중인지

# Mac/Linux 포트 상태 확인 명령어
lsof -i :8080
  1. API 테스트:
    Postman이나 브라우저에서 직접 API 호출 테스트:
  2. 프론트엔드 개발 서버가 5173 포트에서 실행 중인지
  3. 브라우저 콘솔에서 더 자세한 에러 메시지가 있는지

아무리 확인해봐도 API 연결 잘 되어있고, 백엔드 서버 8080에서 실행 중이고, 프론트엔드 개발 서버는 5173포트에서 실행 중이고, 콘솔에는 계속 저 에러만 떠있는데 ㅠㅠㅠ 다른 에러는 없는데 ㅠㅠㅠ 도대체 뭐가 문제인건지 아무것도 모르겠던 그때

문득 스쳐지나간 생각 ..

baseURL: 'http://localhost:8080'

설마 ... 하는 마음으로 확인해보니 localhost 로 되어있는게 아닌가 ㅠㅠㅠㅠㅠㅠ 우리는 지금 서로 다른 컴퓨터로 연결하고 싶어하는데 !!! 'http://localhost:8080'로 연결 백날 해봐라 .. 되냐고 !!!!!!

const api = axios.create({
  baseURL: 'http://백엔드_컴퓨터_IP:8080',  // 예: 'http://192.168.1.100:8080'
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
  }
});

이렇게 백엔드 컴퓨터 IP 주소를 localhost 자리에 넣어주어야 연결이 된다..,,,.... 이렇게 우리는 1시간 동안 삽질 후 다시는 헷갈리지 않게 코드를 꼼꼼하게 보게되었다..!! 이렇게 배우면서 성장하는거지 ... 나만 그런거 아니죠 ..?

0개의 댓글