Stories

Detail Return Return

koa的基本使用 - Stories Detail

1、初始化package.json
npm init
2、安裝koa2
npm install koa
3、hello代碼
ctx.body="hello"必須寫,否則頁面出現Not Found
const koa =require('koa')
const app = new koa()
app.use(async (ctx)=>{
    ctx.body="hello"
})
app.listen(3000)
4、代碼運行
修改代碼時,必須重新運行
index.js為需要運行的文件
node index.js
5、koa-static靜態資源加載
首先安裝koa-static插件npm install koa-static
const Koa = require('koa')
const path = require('path')
const static = require('koa-static')

const app = new Koa()

// 靜態資源目錄對於相對入口文件index.js的路徑
const staticPath = './static'

app.use(static(
  path.join( __dirname,  staticPath)
))

app.use( async ( ctx ) => {
  ctx.body = 'hello world'
})

app.listen(3000, () => {
  console.log('[demo] static-use-middleware is starting at port 3000')
})

Add a new Comments

Some HTML is okay.