코딩/Node.js
[Node] 프론트엔드와 백엔드 연결하여 서버에서 작동구현.
카슈밀
2021. 2. 24. 22:27
반응형
방법은 간단했다.
프론트엔드단에서 npm build나 yarn build로 정적 파일을 구축하고,
이를 서버측에서 이러한 파일을 사용할 수 있도록 라이브러리(koa-static)를 설치하여
정적파일을 읽는 기능을 구현하여 소비자가 요청시에 해당 프로그램을 읽게 연동시키면 된다.
이를 몰라서 어떻게 구현하나 고민이 많았는데, 간단했다.
const buildDirectory = path.resolve(__dirname, "../../blog-frontend/build");
app.use(serve(buildDirectory));
app.use(async ctx => {
// Not Found이고, 주소가 /api로 시작하지 않는 경우
if (ctx.status === 404 && ctx.path.indexOf("/api") !== 0) {
// index.html 내용을 반환
await send(ctx, "index.html", { root: buildDirectory });
}
});
728x90