koa-test
2023年07月14日
const Koa = require("koa");
const KoaRouter = require("koa-router");
const { koaBody } = require("koa-body");
const app = new Koa();
const router = new KoaRouter({ prefix: "/" });
function wait(time) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, time);
});
}
router.get("sync", async (ctx) => {
ctx.body = {
code: 200,
msg: "get 同步请求成功!",
data: ctx.request.query,
};
});
router.get("async", async (ctx) => {
await wait(8000);
ctx.body = {
code: 200,
msg: "get 异步请求成功!",
data: ctx.request.query,
};
});
router.post("sync", async (ctx) => {
ctx.body = {
code: 200,
msg: "post 同步请求成功!",
data: ctx.request.body,
};
});
router.post("async", async (ctx) => {
await wait(8000);
ctx.body = {
code: 200,
msg: "post 异步请求成功!",
data: ctx.request.body,
};
});
app.use(
koaBody({
text: true,
json: true,
multipart: true,
urlencoded: true,
})
);
app.use(router.routes());
app.listen("4000", () => {
console.log("服务启动成功!");
});