admin管理员组文章数量:1597898
前言
POST 接口 跟 GET 请求差不多,只是 POST 接口需要借助 Postman 工具进行请求,因为通过浏览器无法手动发起 POST 请求,只能通过浏览器地址栏发起 GET 请求。
postman 如下:点击加号就可以出现接口配置的
问题
比如我们要访问一个接口实现数据新增
实现
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
控制台也报错了:
WARN 23844 [-/127.0.0.1/-/2ms POST /add] missing csrf token. See https://eggjs/zh-cn/core/security.html#安全威胁csrf的防范
4、报错的原因
Egg 启动的是本地地址 http://127.0.0.1:7001
,但是你请求的 POST 或 GET 接口是非本地计算机(别人的电脑),或者使用 Postman 发起请求,都会触发安防策略。
5、处理报错
可以参考:【https://github/eggjs/egg-security】
在 egg 项目里的 config/config.default.js
做好白名单配置,全部允许请求:
config.security = {
csrf: {
enable: false,
ignoreJSON: true
},
domainWhiteList: [ '*' ], // 配置白名单
};
再次发送接口调用,发现可以了。
6、参数添加
怎么实现参数添加,接口返回数据,比如下面的,结果需要怎么返回
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 请求参数获取 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1728299121a1152799.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论