在Koa.js中實現RESTful API,首先需要安裝koa和koa-router庫。然后創建一個Koa應用實例和一個路由實例。接下來,為每個HTTP方法(如GET、POST、PUT、DELETE等)定義路由處理函數。最后,啟動Koa應用并監聽端口。
以下是一個簡單的示例:
1. 安裝依賴:
npm install koa koa-router
2. 創建一個簡單的Koa應用和路由:
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
// 定義GET請求的處理函數
router.get('/api/resource', async (ctx, next) => {
ctx.body = '獲取資源';
});
// 定義POST請求的處理函數
router.post('/api/resource', async (ctx, next) => {
ctx.body = '創建資源';
});
// 定義PUT請求的處理函數
router.put('/api/resource/:id', async (ctx, next) => {
ctx.body = `更新資源 ${ctx.params.id}`;
});
// 定義DELETE請求的處理函數
router.delete('/api/resource/:id', async (ctx, next) => {
ctx.body = `刪除資源 ${ctx.params.id}`;
});
// 使用路由中間件
app.use(router.routes());
app.use(router.allowedMethods());
// 啟動應用并監聽端口
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
在這個示例中,我們定義了四個路由處理函數,分別對應GET、POST、PUT和DELETE請求。這些處理函數可以根據實際需求進行修改,以實現具體的業務邏輯。