天天看點

egg 項目裡編寫基礎的 POST 接口:使用 POST 請求參數擷取

前言

POST 接口 跟 GET 請求差不多,隻是 POST 接口需要借助 Postman 工具進行請求,因為通過浏覽器無法手動發起 POST 請求,隻能通過浏覽器位址欄發起 GET 請求。

postman 如下:點選加号就可以出現接口配置的

egg 項目裡編寫基礎的 POST 接口:使用 POST 請求參數擷取

問題

比如我們要通路一個接口實作資料新增

實作

Egg 架構内置了 bodyParser 中間件來對 POST 請求 body 解析成 object 挂載到 ​

​ctx.request.body​

​ 上。

1、配置路由

// app/router.js
'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/', controller.home.index);
  router.get('/user/:id', controller.home.user);
  router.post('/add', controller.home.add);
};      

2、配置控制層

// app/controller/home.js
'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }
  async user() {
    const { ctx } = this;
    const { id } = ctx.params;
    ctx.body = id;
  }
  async add() {
    const { ctx } = this;
    ctx.body = "新增頁面";
  }
}

module.exports = HomeController;      

3、postman 通路發現報 403

egg 項目裡編寫基礎的 POST 接口:使用 POST 請求參數擷取

控制台也報錯了:

23844 [-/127.0.0.1/-/2ms POST /add] missing csrf token. See https://eggjs.org/zh-cn/core/security.html#安全威脅csrf的防範      
egg 項目裡編寫基礎的 POST 接口:使用 POST 請求參數擷取

4、報錯的原因

Egg 啟動的是本地位址 ​

​http://127.0.0.1:7001​

​ ,但是你請求的 POST 或 GET 接口是非本地計算機(别人的電腦),或者使用 Postman 發起請求,都會觸發安防政策。

5、處理報錯

可以參考:​​【https://github.com/eggjs/egg-security】​​

egg 項目裡編寫基礎的 POST 接口:使用 POST 請求參數擷取

在 egg 項目裡的 ​

​config/config.default.js​

​ 做好白名單配置,全部允許請求:

config.security = {
  csrf: {
    enable: false,
    ignoreJSON: true
  },
  domainWhiteList: [ '*' ], // 配置白名單
};      
egg 項目裡編寫基礎的 POST 接口:使用 POST 請求參數擷取

再次發送接口調用,發現可以了。

egg 項目裡編寫基礎的 POST 接口:使用 POST 請求參數擷取

6、參數添加

怎麼實作參數添加,接口傳回資料,比如下面的,結果需要怎麼傳回

egg 項目裡編寫基礎的 POST 接口:使用 POST 請求參數擷取

7、修改控制層

添加 ​

​const body = ctx.request.body;​

​ 代碼

'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }
  async user() {
    const { ctx } = this;
    const { id } = ctx.params;
    ctx.body = id;
  }
  async add() {
    const { ctx } = this;
    const body = ctx.request.body;
    ctx.body = body;
  }
}

module.exports = HomeController;      

繼續閱讀