阿里云主机折上折
  • 微信号
Current Site:Index > Steps to initialize a Koa2 project

Steps to initialize a Koa2 project

Author:Chuan Chen 阅读数:62926人阅读 分类: Node.js

Environment Preparation

First, ensure that Node.js and npm/yarn are installed on your system. It is recommended to use Node.js 12.x or higher. You can check the version with the following commands:

node -v
npm -v

It is advisable to use nvm to manage Node.js versions, making it easier to switch between versions required by different projects:

nvm install 14
nvm use 14

Create Project Directory

Create a new project folder and initialize package.json:

mkdir koa2-demo
cd koa2-demo
npm init -y

It is recommended to manually modify the generated package.json to add necessary descriptive information such as author and other fields. Example:

{
  "name": "koa2-demo",
  "version": "1.0.0",
  "description": "A demo Koa2 project",
  "main": "app.js",
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js"
  }
}

Install Koa2 Core Dependencies

Install Koa and commonly used middleware:

npm install koa koa-router koa-bodyparser

If TypeScript support is needed, also install type declarations:

npm install @types/koa @types/koa-router --save-dev

Basic Application Structure

Create app.js as the entry file with the following basic structure:

const Koa = require('koa')
const app = new Koa()

// Response time middleware
app.use(async (ctx, next) => {
  const start = Date.now()
  await next()
  const ms = Date.now() - start
  ctx.set('X-Response-Time', `${ms}ms`)
})

// Response
app.use(async ctx => {
  ctx.body = 'Hello Koa'
})

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000')
})

Route Configuration

Use koa-router to create a route module. Create routes/index.js:

const Router = require('koa-router')
const router = new Router()

router.get('/', async (ctx) => {
  ctx.body = { message: 'Home Page' }
})

router.get('/users', async (ctx) => {
  ctx.body = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' }
  ]
})

module.exports = router

Import the router in app.js:

const router = require('./routes')
app.use(router.routes()).use(router.allowedMethods())

Middleware Integration

Example configuration for commonly used middleware:

const bodyParser = require('koa-bodyparser')
const cors = require('@koa/cors')

// Parse request body
app.use(bodyParser({
  enableTypes: ['json', 'form'],
  formLimit: '10mb'
}))

// CORS support
app.use(cors({
  origin: '*',
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE']
}))

// Error handling
app.use(async (ctx, next) => {
  try {
    await next()
  } catch (err) {
    ctx.status = err.status || 500
    ctx.body = { error: err.message }
    ctx.app.emit('error', err, ctx)
  }
})

Configuration Management

Use dotenv to manage environment variables. Install the dependency:

npm install dotenv

Create a .env file:

PORT=3000
DB_HOST=localhost
DB_PORT=27017

Load the configuration at the top of app.js:

require('dotenv').config()
const PORT = process.env.PORT || 3000

Logging

It is recommended to use the koa-logger middleware:

npm install koa-logger

Integrate into the application:

const logger = require('koa-logger')
app.use(logger())

Example of custom log format:

app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

Static File Serving

Use koa-static to serve static resources:

npm install koa-static

Example configuration:

const serve = require('koa-static')
const path = require('path')

app.use(serve(path.join(__dirname, 'public'), {
  maxage: 365 * 24 * 60 * 60 * 1000 // Cache for one year
}))

Database Connection

For MongoDB, use mongoose:

npm install mongoose

Create a db.js connection file:

const mongoose = require('mongoose')

const connectDB = async () => {
  try {
    await mongoose.connect(process.env.DB_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    })
    console.log('MongoDB Connected...')
  } catch (err) {
    console.error(err.message)
    process.exit(1)
  }
}

module.exports = connectDB

Call it in app.js:

const connectDB = require('./db')
connectDB()

Project Structure Optimization

Recommended project directory structure:

├── app.js
├── config/
│   └── index.js
├── controllers/
│   └── userController.js
├── models/
│   └── User.js
├── middlewares/
│   └── auth.js
├── routes/
│   ├── index.js
│   └── api/
│       ├── user.js
│       └── product.js
├── public/
│   ├── images/
│   └── styles/
└── utils/
    └── logger.js

Development Tool Configuration

Install nodemon for hot reloading:

npm install nodemon --save-dev

Modify package.json scripts:

{
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon --watch '**/*.js' --exec node app.js",
    "test": "jest"
  }
}

Add a .gitignore file:

node_modules/
.env
.DS_Store
logs/
*.log

Test Environment Setup

Use Jest for unit testing:

npm install jest supertest --save-dev

Create a test file tests/app.test.js:

const request = require('supertest')
const app = require('../app')

describe('GET /', () => {
  it('should return 200 OK', async () => {
    const res = await request(app.callback()).get('/')
    expect(res.status).toBe(200)
  })
})

Deployment Preparation

Add a PM2 configuration file ecosystem.config.js:

module.exports = {
  apps: [{
    name: 'koa-app',
    script: 'app.js',
    instances: 'max',
    autorestart: true,
    watch: false,
    max_memory_restart: '1G',
    env: {
      NODE_ENV: 'production',
      PORT: 3000
    }
  }]
}

Performance Optimization

Enable gzip compression:

npm install koa-compress

Example configuration:

const compress = require('koa-compress')

app.use(compress({
  threshold: 2048,
  gzip: {
    flush: require('zlib').constants.Z_SYNC_FLUSH
  },
  deflate: {
    flush: require('zlib').constants.Z_SYNC_FLUSH
  },
  br: false
}))

Security Hardening

Common security middleware:

npm install koa-helmet koa-rate-limit

Example configuration:

const helmet = require('koa-helmet')
const rateLimit = require('koa-rate-limit')

app.use(helmet())
app.use(rateLimit({
  interval: { min: 15 }, // 15 minutes
  max: 100 // Max 100 requests per IP
}))

Error Monitoring

Integrate Sentry for error tracking:

npm install @sentry/node

Example configuration:

const Sentry = require('@sentry/node')

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  tracesSampleRate: 1.0
})

app.on('error', (err, ctx) => {
  Sentry.captureException(err)
})

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.