获取get
// 引入类
const Koa=require('koa');
const Router=require('koa-router');
// 引入内部方法或属性
// const{方法或属性名}=require('koa);
// 创建对象
const app =new Koa();
const router =new Router();//创建路由
// response
app.use(ctx=>{
ctx.body = 'Hello koa';
});
router.get("/",async ctx=>{
console.log(ctx.URL);
})
// 调用router.routes()来组装匹配好的路由,返回一个合并好的中间件
// 调用router.allowedMethods()获得一个中间件,当发送了不符合的请求时,会返回 `405 Method Not Allowed` 或 `501 Not Implemented`
app.use(router.routes());
app.use(router.allowedMethods({
// throw: true, // 抛出错误,代替设置响应头状态
// notImplemented: () => '不支持当前请求所需要的功能',
// methodNotAllowed: () => '不支持的请求方式'
}));
// app.use(router.routes().use(router.allowedMethods({ }));
// localhost:3001
app.listen(3001,()=>{
console.log("http://localhost:3001")
});
从终端安装插件 npm i koa-router --save
然后运行 nodemon app.js
从"http://localhost:3001"网址中传参数?id=1001
回到终端输出id
获取post
// 引入类
const Koa=require('koa');
const Router=require('koa-router');
const koaBody=require('koa-body');
// 引入内部方法或属性
// const{方法或属性名}=require('koa);
// 创建对象
const app =new Koa();
app.use(koaBody());
const router =new Router();//创建路由,支持传递参数
// response
app.use(async(ctx,next)=>{
ctx.body = 'Hello koa';
next();
});
router.get("/",async (ctx)=>{
// url参数 ctx.query
console.log(ctx.url);
console.log(ctx.query);
// console.log(ctx.querystring);
})
// postman 测试后端接口
router.post("/",async ctx=>{
console.log(ctx.url);
console.log(ctx.request.body);
})
// 调用router.routes()来组装匹配好的路由,返回一个合并好的中间件
// 调用router.allowedMethods()获得一个中间件,当发送了不符合的请求时,会返回 `405 Method Not Allowed` 或 `501 Not Implemented`
app.use(router.routes());
app.use(router.allowedMethods({
// throw: true, // 抛出错误,代替设置响应头状态
// notImplemented: () => '不支持当前请求所需要的功能',
// methodNotAllowed: () => '不支持的请求方式'
}));
// app.use(router.routes().use(router.allowedMethods({ }));
// localhost:3001
app.listen(3001,()=>{
console.log("http://localhost:3001")
});
需要新建一个text.http
点击上方的Send Request可以输出
![]()