NodeJS Express와 VueJS 연동하기

김상선·2022년 12월 19일
0

NodeJS 앱들을 PM2로 관리하기 위해서 VueJS에 express 서버를 연결해서 구동시켰습니다.

VueJS나 React 같은 싱글 페이지(SPA)로 구성된 어플리케이션은
express 서버에서 랜딩 페이지가 아닌 하위 페이지로 직접 접근하거나, 새로고침을 누르면 404 에러가 생겼습니다.

이를 해결하기 위해 connect-history-api-fallback 이라는 미들웨어를 사용했습니다.
express 서버에서 요청을 보내도, Vue Router에서 API를 요청한 것으로 변환해줍니다.

const express = require("express");
const history = require("connect-history-api-fallback");
const app = express();
const path = require("path");

app.set("port", process.env.PORT || 8000);

app.use(history()); //라우터보다 먼저 실행되야함
app.use(express.static(path.join(__dirname, "dist"))); //dist는 클라이언트 view폴더


app.get("/", function (req, res, next) {
  res.sendFile(path.join(__dirname, "dist/index.html")); //클라이언트 html 라우터 연결
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

app.listen(app.get("port"), () => {
  console.log(`Server is running on port ${app.get("port")}`);
});

https://yorr.tistory.com/6?category=753153

profile
일요일을 좋아합니다.

0개의 댓글