本文爲我的學習整理所得,但願對讀者有所幫助。javascript
在通常狀況下,項目中會有兩種get傳參方式:1 是以?
和&
分割的、2 是以/
分割;html
例如客戶端向傳遞約定的id
和name
這兩個參數:java
localhost:7001/goods/detail?id=2333&name=hefennode
localhost:7001/goods/detail/2333/hefengit
對應的,在服務器接收這兩個參數的方式:1 query
方式、2 params
,如下是代碼示例:github
detail
:// GET
async detail() {
const { ctx } = this;
console.log(ctx.query);
ctx.body = `hello, my id is ${ctx.query.id} and my name is ${ctx.query.name}`;
}
複製代碼
瀏覽器中輸入連接1 -- localhost:7001/goods/detail?id=2333&name=hefen,能夠看到界面已經把數據讀取出來了:json
這時候咱們再看控制檯的打印結果:瀏覽器
detailTwo
:// GET
async detailTwo() {
const { ctx } = this;
console.log(ctx.params);
ctx.body = `hello, detailTwo, my id is ${ctx.params.id} and my name is ${ctx.params.name}`;
}
複製代碼
而後在app/router.js中加入新的路由:服務器
router.get('/goods/detailTwo/:id/:name', controller.goods.detailTwo);
複製代碼
由於POST請求不能直接在瀏覽器模擬,因此接下來咱們會藉助了接口神器 postman 來測試接口。 固然直接發送請求的話會觸發egg.js
內置的csrf
防護機制,控制檯報錯以下圖:(PS:更多防護機制請看官方文檔點擊此處)app
這個時候咱們須要在config/config.default.js中配置一下,就能夠正常使用了
config.security = {
csrf: {
enable: false, //此處關閉csrf防護
}
}
複製代碼
用postman選擇POST方式,輸入接口localhost:7001/goods/detail/createGood,勾選body,raw,JSON格式,填入json對象後,點擊發送,以下圖:
在app/controllergoods.js中,新建一個函數createGood
:
// POST
async createGood() {
const { ctx } = this;
const { name, id } = ctx.request.body;
console.log(ctx.request.body);
ctx.body = {
id:`back ${id}`,
name:`back ${name}`,
}
}
複製代碼
而後在app/router.js中加入新的路由:
router.post('/goods/createGood', controller.goods.createGood);
複製代碼
這時候咱們再看控制檯的打印結果:
這兩種的調用方式與上面的請求大同小異,須要的童鞋能夠看我在github放出的源碼。
這節如要熟悉請求方式,因此。。
PS:所有的代碼倉庫:github.com/hejian1993/…,暫時沒有分章節,僅供參考。
我是河粉,咱們下一節見
三個月前,一我的關注了我,他娶了一個如花似玉的老婆。 一週前,一我的關注了我,他中了888億。 今年,關注了個人人都娶了如花似玉的老婆結婚那天還中888億。 我已開過光,話已經放到這了。