基於node+koa實現的mock數據接口,Koa須要v7.6.0以上node版本,低於此版本請先升級node
// server.js const Koa = require('koa'); const Router = require('koa-router'); const qs = require('qs'); const assert = require('assert'); const app = new Koa(); const router = new Router(); /** * 獲取列表數據 * @param {request} page 頁數 * @param {request} limit 每頁數據條數 * @param {response} errno 返回狀態碼 0 ==> 返回成功 1 ==> 有錯誤 * @param {response} hasMore 是否有更多數據 */ let listData = require('./mock/list/list.js'); router.get('/api/getlist/:page/:limit', function (ctx, next) { const page = ctx.params.page; const limit = ctx.params.limit; const maxPage = listData.length / limit; // 構造返回對象 let res = { errno: 0, data: { hasMore: true, data: [] } }; // 若是超過最大頁面數 if ((page*1 + 1) >= maxPage) { res.data.hasMore = false; } res.data.data = listData.slice(page*limit, page*limit + limit); ctx.body = res; }); /** * 獲取詳情數據 * @param {request} id 商品id */ const detailData = require('./mock/detail/detail.js'); router.get('/api/getdetail/:id', function (ctx, next) { const id = ctx.params.id let res = { errno: 0, data: { data: [] } } res.data.data = detailData; // todo... ctx.body = res; }); /** * 提交評論 * @param {request} id 用戶id * @param {request} uid 商品id * @param {request} msg 評論內容 */ router.post('/api/comment', function (ctx, next) { const params = qs.parse(ctx.req._parsedUrl.query); const id = params.id; const uid = params.uid; const msg = params.msg; if (id === undefined || uid === undefined || msg === undefined) { ctx.body = { errno: 1, msg: '缺乏參數' } } else { // todo... ctx.body = { errno: 0, msg: '評論成功' } } }); app .use(router.routes()) .use(router.allowedMethods()); app.listen(3000); console.log("server is running at http://localhost:3000/");
module.exports = { ... devServer: { proxy: { // 將 `/api` 開頭的 http 請求,都代理到 `localhost:3000` 上,由 koa 提供 mock 數據 '/api': { target: 'http://localhost:3000', secure: false } } ... } }
https://github.com/daijingfeng/mock-server
喜歡的朋友就賞個star吧
node