0
点赞
收藏
分享

微信扫一扫

egg 项目里编写基础的 POST 接口:使用 POST 请求参数获取


前言

POST 接口 跟 GET 请求差不多,只是 POST 接口需要借助 Postman 工具进行请求,因为通过浏览器无法手动发起 POST 请求,只能通过浏览器地址栏发起 GET 请求。

postman 如下:点击加号就可以出现接口配置的

egg 项目里编写基础的 POST 接口:使用 POST 请求参数获取_egg

问题

比如我们要访问一个接口实现数据新增

实现

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 请求参数获取_白名单_02

控制台也报错了:

23844 [-/127.0.0.1/-/2ms POST /add] missing csrf token. See https://eggjs.org/zh-cn/core/security.html#安全威胁csrf的防范

egg 项目里编写基础的 POST 接口:使用 POST 请求参数获取_白名单_03

4、报错的原因

Egg 启动的是本地地址 ​​http://127.0.0.1:7001​​ ,但是你请求的 POST 或 GET 接口是非本地计算机(别人的电脑),或者使用 Postman 发起请求,都会触发安防策略。

5、处理报错

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

egg 项目里编写基础的 POST 接口:使用 POST 请求参数获取_egg_04

在 egg 项目里的 ​​config/config.default.js​​ 做好白名单配置,全部允许请求:

config.security = {
csrf: {
enable: false,
ignoreJSON: true
},
domainWhiteList: [ '*' ], // 配置白名单
};

egg 项目里编写基础的 POST 接口:使用 POST 请求参数获取_postman_05

再次发送接口调用,发现可以了。

egg 项目里编写基础的 POST 接口:使用 POST 请求参数获取_数据_06

6、参数添加

怎么实现参数添加,接口返回数据,比如下面的,结果需要怎么返回

egg 项目里编写基础的 POST 接口:使用 POST 请求参数获取_javascript_07

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;

修改完再次访问,发现就有了。

egg 项目里编写基础的 POST 接口:使用 POST 请求参数获取_白名单_08


举报

相关推荐

0 条评论