Vue.js/Nuxt

Nuxt에서 Express 사용법

mean-ji 2022. 8. 22. 10:24
728x90

Nuxt는 디렉토리와 파일명 생성 구조에 따라 라우팅이 자동으로 되는 편리함이 있어서 간단한 프로젝트에는 따로 Express로 미들웨어를 구성할 필요가 없을 것 같다. 하지만 라우팅시, html, js 이전에 어떤 작업이 필요하다면 (Spring의 Controller와 같은? 이 비유가 맞는지 아직 확실하진 않지만) 아무튼 그 작업이 필요해서 Express를 사용하게 되었다.

Nuxt에도 created, mounted등의 함수로 간편하게 구현할 수 있지만 html이 필요하지 않은 상황에 디렉토리와 파일을 생성하는 것보다 Express를 이용하면 더 깔끔할 것이라 생각이 들었다.

 

++ 추가로 Express를 먼저 공부한 후 Nuxt에 Express를 적용해 보았다.

https://mean-ji.tistory.com/4

Middleware

클라이언트에게 요청이 오고 그 요청을 보내기 위해 응답하려는 중간에 목적에 맞게 처리를 하는 함수들이다.

Express 사용법

설치

yarn add express

설정 파일 변경

nuxt.config.js

serverMiddleware: ['~/api/index.js']

api/index.js 파일 생성 및 Express 코드 작성

root에 api 디렉토리를 생성하고 아래의 파일을 작성합니다.

const express = require('express')
const app = express()

app.get('/', function (request, response) {
    response.send('Hello World!');
});

const sample = require('./routes/sample')
app.use('/sample', sample);

module.exports = {
    path: '/api',
    handler: app
}

 

localhost:3000/api 로 접속하면 Hello World!가 출력되는 것을 볼 수 있다.

 

route 분리도 가능한데, 블로그 참고해보니

./api/routes 폴더에 sample.js라는 파일을 생성하여 route 기능을 분리하는 예시였다.

const { Router } = require('express')
const router = Router()

router.get('/', function (req, res) {
    res.send('Hello')
})

router.get('/world', function (req, res) {
    res.send('World!')
})

const sampleController = require('../controller/sampleController')
router.post('/test', sampleController.test)

module.exports = router

 

controller도 사용할 수 있는데, ./api/controller에 sampleController.js 파일을 생성한다.

module.exports.test = function (req, res) {
    res.send('Hello World')
}

Reference

 

https://nuxtjs.org/docs/configuration-glossary/configuration-servermiddleware/

https://psyhm.tistory.com/8

728x90