반응형

package.json

{
    "scripts": {
        "start:local": "nodemon --watch src/ src/index.js",
        "start:dev": "node src/index.js"
    },
    "dependencies": {
        "koa": "^2.11.0",
        "koa-bodyparser": "^4.3.0",
        "koa-router": "^8.0.8"
    },
    "devDependencies": {
        "nodemon": "^2.0.3"
    }
}

의존성 설치

yarn install

example1.js

  • 경로 : <프로젝트>/src/routes/api/example1.js
const Router = require('koa-router');
const router = new Router();

router.get('/example1/:value1', async (ctx) => {
    const { value1 } = ctx.params;
    const { value2 } = ctx.query;
    const { cookie } = ctx.headers;

    console.log(value1, value2, cookie);

    ctx.body = 'get';
});

router.post('/example1', async (ctx) => {
    const requestBody = ctx.request.body;

    console.log(requestBody);

    ctx.set('example-header', 'Hello World');
    ctx.body = { result: 'success' };
});

module.exports = router;

logger.js

  • 경로 : <프로젝트>/src/middleware/logger.js
const logger = async (ctx, next) => {
    const start = Date.now();
    await next();

    const responseTime = Date.now() - start;
    const { method, url } = ctx.request;
    const { status } = ctx.response;

    console.log(`[${method}] [${url}] [${status}] [${responseTime}]`);
};

module.exports = () => logger;

routes.js

  • 경로 : <프로젝트>/src/middleware/routes.js
const Router = require('koa-router');
const fs = require('fs');

const router = new Router();
const routeContexts = fs.readdirSync('./src/routes');

routeContexts.forEach((routeContext) => {
    const routeFiles = fs.readdirSync(`./src/routes/${routeContext}`);

    routeFiles.forEach((routeFile) => {
        const route = require(`../routes/${routeContext}/${routeFile}`);
        router.use(`/${routeContext}`, route.routes());
    });
});

module.exports = () => router.routes();

index.js

  • 경로 : <프로젝트>/src/index.js
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const logger = require('./middleware/logger');
const routes = require('./middleware/routes');

const app = new Koa();
const router = new Router();

router.use(routes());

app.use(logger());
app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000, () => {
    console.log('server started');
});

실행

yarn start:local

접속

반응형

+ Recent posts