基于node+koa實(shí)現(xiàn)的mock數(shù)據(jù)接口,Koa需要v7.6.0以上node版本,低于此版本請(qǐng)先升級(jí)node
目錄結(jié)構(gòu)
// 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(); /** * 獲取列表數(shù)據(jù) * @param {request} page 頁(yè)數(shù) * @param {request} limit 每頁(yè)數(shù)據(jù)條數(shù) * @param {response} errno 返回狀態(tài)碼 0 ==> 返回成功 1 ==> 有錯(cuò)誤 * @param {response} hasMore 是否有更多數(shù)據(jù) */ 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; // 構(gòu)造返回對(duì)象 let res = { errno: 0, data: { hasMore: true, data: [] } }; // 如果超過(guò)最大頁(yè)面數(shù) if ((page*1 + 1) >= maxPage) { res.data.hasMore = false; } res.data.data = listData.slice(page*limit, page*limit + limit); ctx.body = res; }); /** * 獲取詳情數(shù)據(jù) * @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; }); /** * 提交評(píng)論 * @param {request} id 用戶id * @param {request} uid 商品id * @param {request} msg 評(píng)論內(nèi)容 */ 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: '缺少參數(shù)' } } else { // todo... ctx.body = { errno: 0, msg: '評(píng)論成功' } } }); app .use(router.routes()) .use(router.allowedMethods()); app.listen(3000); console.log("server is running at http://localhost:3000/");
實(shí)際項(xiàng)目中,調(diào)用接口會(huì)遇到跨域的問(wèn)題,解決的方式有多種,這里介紹如何在webpack中配置
module.exports = { ... devServer: { proxy: { // 將 `/api` 開(kāi)頭的 http 請(qǐng)求,都代理到 `localhost:3000` 上,由 koa 提供 mock 數(shù)據(jù) '/api': { target: 'http://localhost:3000', secure: false } } ... } }
項(xiàng)目地址:https://github.com/daijingfeng/mock-server
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com