egg如何扩展response

简介: egg如何扩展response

response扩展插件


1、在app/extend目录下新建response.js文件


例如 新建一个设置token的response.js的扩展插件


module.exports = {
    set token(token) {
        this.set('token', token)
    }
}


2、在控制层controller里某个控制的js里写入方法


例如我在test.js里面写入


'use strict';
const Controller = require('egg').Controller;
classTestController extends Controller {
    async newResponse() {
        const { ctx } = this;
        ctx.response.token = 'weblod'
        ctx.body = 'wxinxianyun'
    }
}
module.exports = TestController;


3、然后在router.js里添加刚才的路由


'use strict';
/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
    const counter = app.middleware.counter();
    const { router, controller } = app;
    router.post('/test', controller.test.index);
    router.post("/test/add", controller.test.add);
    router.post("/test/del", controller.test.del);
    router.post("/test/edit", controller.test.edit);
    router.post("/test/look", controller.test.look);
    router.get("/test/newResponse", controller.test.newResponse);
};


最后在地址栏输入http://localhost:7001/test/newResponse就能看到请求头设置的token了

相关文章
|
5月前
|
JSON 程序员 数据格式
深入探索 “JSON for Modern C++“:安装、构建与应用
深入探索 “JSON for Modern C++“:安装、构建与应用
129 0
|
5月前
|
Java
【极问系列】springBoot集成elasticsearch出现Unable to parse response body for Response
【极问系列】springBoot集成elasticsearch出现Unable to parse response body for Response
690 2
|
10月前
ERROR Plugin load failed: hexo-generator-json-content
ERROR Plugin load failed: hexo-generator-json-content
55 0
|
中间件
egg的middleware和application的配置(五)
Context 实例,通常我们也简写成 ctx。在所有的文档中,Context 和 ctx 都是指 Koa 的上下文对象。
egg的middleware和application的配置(五)
|
PyTorch 算法框架/工具
Bert模型之unable to parse config.json as a URL or as a local path错误解决方案
Bert模型之unable to parse config.json as a URL or as a local path错误解决方案
1020 0
Bert模型之unable to parse config.json as a URL or as a local path错误解决方案
|
Web App开发 JSON 前端开发
前端必备的谷歌浏览器JSON可视化插件:JSON-Handle
前端必备的谷歌浏览器JSON可视化插件:JSON-Handle
787 0
前端必备的谷歌浏览器JSON可视化插件:JSON-Handle
|
前端开发 Java API
swagger2 统一默认Response Code
swagger2 统一默认Response Code
430 0
|
JSON API 数据格式
Swoole v4.5.7 版本发布,新增--enable-swoole- json编译选项
在上个版本中添加的 swoole_substr_json_decode 函数,由于少部分用户的扩展依赖顺序问题,所以添加了一个编译选项--enable-swoole-json,用于启用 swoole_substr_json_decode 支持
172 0
|
Python
Python 库升级问题-module ‘requests.exceptions‘ has no attribute ‘ReadTimeout‘原因及解决办法
Python 库升级问题-module ‘requests.exceptions‘ has no attribute ‘ReadTimeout‘原因及解决办法
370 0
Python 库升级问题-module ‘requests.exceptions‘ has no attribute ‘ReadTimeout‘原因及解决办法
|
JSON 数据格式
SAP UI5 createBindingContext in local JSON model
Created by Wang, Jerry, last modified on May 01, 2016
106 0
SAP UI5 createBindingContext in local JSON model