終端:
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":"張三" }