微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Ajax匹配路由器

//引入对象 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("/a",async ctx=>{     console.log(ctx.url);     console.log(ctx.request.body);     ctx.body="请求成功" })
//调用router.routes()来组装匹配好的路由,返回一个合并好的中间件 //调用router.allowedMethods()获得一个中间件,当发送了不符合的请求时,会返回405 app.use(router.routes()).use(router.allowedMethods()); //localhost:3000 app.listen(8000,()=>{     console.log("http://localhost:8000"); }); HTML内容: POST http://localhost:8000/a HTTP/1.1 Content-Type: application/json
{     "id":1000,     "name":"张三" }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐