终端:
1.安装koa-router
npm i koa-router --save //i指install
2. 用 nodemon 来代替 node 来启动应用
nodemon app.js
效果如下:
app.js的代码的步骤
//引入类 //引入内部方法或属性 //const{方法或属性名}=request('koa); const Koa = require('koa'); //const后面的Koa定义的首字母为大写,并且要与下面创建的路由要一致 const Router=require('koa-router'); //使用原生的对数据进行解析,操作稍显复杂,引入koa-body,解析用post方式获取里的数据 const koaBody=require('koa-body');
//创建对象
const app = new Koa();
app.use(koaBody()); //使用koabody()
const router=new Router();//创建路由,支持传递参数
//get方式 支持异步函数 async---形参
router.get("/",async (ctx)=>{
//url参数 ctx.query
console.log(ctx.url);//获取带参数的路由地址
console.log(ctx.query);//获取的json对象
console.log(ctx.querystring);//获取纯字符串
})
//postman post方法
router.post("/a",async ctx=>{
console.log(ctx.url);
console.log(ctx.request.body);//request.body请求
ctx.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:4000 监听端口里的内容(或地址)
app.listen(4000,()=>{
console.log("http:localhost:4000")
});
test.html中的代码:(因为post是从页面获取数据,所以需要借助test.html)
POST http://localhost:4000/a HTTP/1.1 Content-Type: application/json //参数解析 //首先明确一点,这也是一种文本类型(和text/json一样),表示json格式的字符串,如果ajax中设置为该类型,则发送的json对象必须要使用JSON.stringify进行序列化成字符串才能和设定的这个类型匹配。 # 上面和下面必须得空一行 # content # 一个是表单方式 id=1000&name=张三 另一个是json方式 # 必须用双引号 { "id":1000, "name":"张三" }