//引入模块
const Koa = require("koa");
const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");
const fs = require("fs");
const path = require("path");
const os = require("os");
const moment = require("moment");
//实例化
const app = new Koa();
const router = new Router();
const port = "5050";
const host = (() => {
let address = "";
const interfaces = os.networkInterfaces(); //建立接口
Object.values(interfaces).find(item => {
const result = item.find(
({ family, internal }) => family === "IPv4" && internal === false,
);
if (result) {
address = result.address;
return true;
}
});
return address;
})();
//请求处理
app.use(async (ctx, next) => {
await next();
console.log(`${ctx.method} ${ctx.url}`);
});
app.use(bodyParser());
router
.all("/", (ctx, next) => {
ctx.body = `<h1 align="center" style="color: red">舒适提示:请求路径不正确!</h1>`;
})
.all("/index.html", (ctx, next) => {
ctx.body = fs.readFileSync(__dirname + "/index.html", "utf8");
})
.all(["/app/api/", "/app/api/:apiName"], async (ctx, next) => {
await next();
const apiName = ctx.params.apiName;
const method = ctx.request.method;
let request_data = {};
if (method === "GET") {
request_data = ctx.request.query;
} else {
request_data = ctx.request.body;
}
let body = createResponseData("无数据");
const type = [".js", ".json"].find(item => {
return fs.existsSync(
path.resolve(__dirname, "data", apiName + item),
);
});
const filePath = path.resolve(__dirname, "data", apiName + type);
if (type === ".json") {
body = fs.readFileSync(filePath, "utf8");
} else if (type === ".js") {
body = await require(filePath)(request_data);
}
ctx.type = "application/json;charset=utf-8";
ctx.body = body;
});
app.use(router.routes()).use(router.allowedMethods());
//建立服务器
app.listen(port);
console.log(`mockServer runing on ${host}:${port}`);
//响应数据建立辅助方法
const createResponseData = (response_data, response_header = {}) => {
return {
header: Object.assign(
{
res_code: "0000",
res_desc: "接口数据请求成功",
responseTime: moment().format("YY-MM-DD hh:mm:ss"),
},
response_header,
),
response: response_data,
};
};
module.exports = { createResponseData };
复制代码
const server = require("../server");
module.exports = request_data => {
const { heroId } = request_data;
console.log("请求入参" + heroId);
return new Promise((resolve, reject) => {
const response_header = {};
const response_data = server.createResponseData(MockData.get(heroId));
resolve(response_data, response_header);
});
};
//模拟的数据
const MockData = new Map([[key, value],[key, value]]);
复制代码
连接:koa官网css
const Koa = require('koa');
const app = new Koa();
app.listen(3000);
app.context.db = db(); //经过编辑 app.context 为 ctx 添加其余属性
app.use(async (ctx, next) => {
await next();
ctx.body = 'Hello World';
});
app.use(async ctx => {
console.log(ctx.db);
});
app.on('error', (err, ctx) => { //添加错误事件监听器
log.error('server error', err, ctx);
});
复制代码
ctx.state.user = await User.find(id);html
signed 所请求的cookie应该被签名json
maxAge 一个数字表示从 Date.now() 获得的毫秒数
signed cookie 签名值
expires cookie 过时的 Date
path cookie 路径, 默认是'/'
domain cookie 域名
secure 安全 cookie
httpOnly 服务器可访问 cookie, 默认是 true
overwrite 一个布尔值,表示是否覆盖之前设置的同名的 cookie (默认是 false). 若是是 true, 在同一个请求中设置相同名称的全部 Cookie(无论路径或域)是否在设置此Cookie 时从 Set-Cookie 标头中过滤掉。
复制代码
ctx.header
ctx.headers
ctx.method
ctx.method=
ctx.url
ctx.url=
ctx.originalUrl
ctx.origin
ctx.href
ctx.path
ctx.path=
ctx.query
ctx.query=
ctx.querystring
ctx.querystring=
ctx.host
ctx.hostname
ctx.fresh
ctx.stale
ctx.socket
ctx.protocol
ctx.secure
ctx.ip
ctx.ips
ctx.subdomains
ctx.is()
ctx.accepts()
ctx.acceptsEncodings()
ctx.acceptsCharsets()
ctx.acceptsLanguages()
ctx.get()
复制代码
ctx.body
ctx.body=
ctx.status
ctx.status=
ctx.message
ctx.message=
ctx.length=
ctx.length
ctx.type=
ctx.type
ctx.headerSent
ctx.redirect()
ctx.attachment()
ctx.set()
ctx.append()
ctx.remove()
ctx.lastModified=
ctx.etag=
复制代码
>> 为属性赋值则为设置属性值,如:request.headers= 为设置请求头 <<
request.headers //请求标头对象,别名request.header。
request.method //请求方法。
request.length //请求的 Content-Length, Number或 undefined
request.url //获取请求 URL.
request.originalUrl //获取请求原始URL。
request.origin //获取URL的来源,包括 protocol(协议) 和 host。
request.href //获取完整的请求URL,包括 protocol,host 和 url(路由传参)。
request.path //获取请求路径名。
request.querystring //获取原始查询字符串。
request.search //获取原始查询字符串。
request.host //获取当前主机(hostname:port)
request.hostname //获取主机名
request.type //获取请求Content-Type
request.charset //获取请求字符集, 如utf-8
request.query //获取查询字符串对象
request.protocol //获取请求协议
复制代码
response.headers
response.socket //请求套接字。
response.status //获取响应状态。
response.message //获取响应的状态消息
response.length
response.body //获取响应主体。
response.type
response.redirect(url, [alt]) //重定向到 url。
response.attachment([filename], [options]) //将 Content-Disposition 设置为 “附件” 以指示客户端提示下载
response.flushHeaders() //刷新任何设置的标头,并开始主体。
复制代码