[error note] React 와 Node 서버 연동 시 404 error

바다·2023년 2월 13일
0

Node

목록 보기
1/3
post-thumbnail

1. Error 당시 상황

React 프로젝트에 node.js를 이용한 서버를 연동시키고자 했고 인터넷으로 찾은 방법을 이용해 코드를 작성했다.
그러나, index.html에서 js,css,manifest.json 파일의 경로가 잘못되어 해당 파일들을 불러오지 못하는 404 에러가 발생했다.

파일

  • client 폴더는 react 로 만든 프로젝트가 담긴 폴더이다.
  • client/build 에는 client/build/index.html이 불러온 json,js,css 파일들이 있다.

2. Error 원인

404 에러는 server.js와 build/index.html에서 파일들을 불러오는 경로가 서로 맞지 않음을 의미하고 이러한 원인은 client를 github 저장소에 업로드 했기 때문에 발생했다.

github 저장소를 연결하지 않은 CRA 프로젝트와 달리, 해당 프로젝트에서 index.html은 파일의 경로에 static 앞에 github저장소 이름이 붙었다.

인터넷에서 찾은 페이지에서는 github에 업로드 하지 않았기 때문에 페이지에서 보여준 사례에서는 404 error가 발생하지 않은 것이였다.

client/build/index.html

<!--....-->
<link rel="manifest" href="/weather_react/manifest.json"/>
<title>Weather</title>
<script defer="defer" src="/weather_react/static/js/main.17b119d6.js"></script>
<link href="/weather_react/static/css/main.65e4cede.css" rel="stylesheet">
  • weather_react : github 저장소

server.js

const express =require('express');
const app = express();
const port = 5000;
const path = require('path');

app.use(express.static(path.join(__dirname, './client/build')));
/*
app.use([path,] callback [, callback...]) 
path 의 default 는 '/'
*/
app.get('/', function (req, res) {
  res.sendFile( path.join(__dirname, './client/build/index.html'));
});
app.listen(port, ()=>{
  console.log("hello server")
})

개발환경에서 설명하자면, localhost:5000 에서 서버를 열 경우, 서버는 ./client/build/index.html을 프론트에 전달한다. 전달된 index.html은 localhost:5000/weather_react/~ 에서 json,js,css파일을 불러오려 하지만 ./client/build 폴더는 localhost:5000/weather_react/~ 에서 사용되지 않기 때문에 불러올 파일들의 경로를 찾을 수 없는 에러가 발생한 것이다.

즉, index.html이 불러온 파일들이 있는 client/build는 localhost:5000 에 있는데 index.html는 localhost:5000/weather_react/~ 에서 파일들을 요청했기 때문에 404 에러가 발생했다.

3. Error 해결방법

404에러를 해결할 방법은 server.js에서 build 폴더를 사용할 경로와 index.html에서 파일들을 불러올 경로를 일치하도록 수정하는 것이다.

방법1. server.js 경로 수정

server.js 에서 app,use와 app.get의 path를 '/'에서 '/weather_react'로 수정)

  • server.js
 app.use('/weather_react',express.static(path.join(__dirname, './client/build')));

app.get('/weathter_react', function (req, res) {
  res.sendFile( path.join(__dirname, './client/build/index.html'));
});
  • 수정 시 개발자 소스 (localhost:5000/weather_react)

방법2. index.html 경로 수정

build/index.html에서 파일을 불러오는 경로에서 weather_react를 제거한다.

  • build/index.html
	....
<link rel="manifest" href="/weather_react/manifest.json"/>
<title>Weather</title>
<script defer="defer" src="/static/js/main.17b119d6.js"></script>
<link href="/static/css/main.65e4cede.css" rel="stylesheet">
  • 수정 시 개발자 소스 (localhost:5000)

만약 react를 더 이상 수정할 필요가 없다면 방법2도 괜찮지만, css나 js파일들의 수정이 필요하다면 방법1을 선택해야한다. 왜냐하면 파을을 수정후 build 하면 index.html은 다시 github 저장소의 이름을 경로가 가지게 되는데 그러면 또 다시 index.html의 경로를 수정해야해서 번거롭기 때문이다.

profile
🐣프론트 개발 공부 중 (우테코 6기)

0개의 댓글