node.js - Monkey Patch 在发送响应之前重新调整响应
问题描述
我正在尝试在我的restify json响应中应用 JSON 掩码(与 Friday 13th 游戏或电影无关) 。
正常的做法是在所有服务器路由中调用 next(),然后在 restify 的 'pre' 处理程序中实现掩码
我现在不能这样做,我要快速修复,所以我正在尝试猴子修补我的 restify 响应,如下所示:
创建一个模块“CustomResponse”:
function CustomResponse (originalResponse) {
this.restifyResponse = originalResponse
this.type = 'customResponse'
}
CustomResponse.prototype.send = function (code, payload) {
if (!payload) { payload = code }
console.log(payload)
this.restifyResponse.send(code, payload)
}
module.exports = CustomResponse
我正在尝试在中间件中使用此模块,但它不起作用:
var CustomResponse = require('./customResponse') // the file above
server.use(function (req, response, next) {
response = new customResponse(response)
next()
})
这仅在我在路线中使用时才有效:
var CustomResponse = require('./customResponse') // the file above
server.get({
path: '/foo/bar'
}, function(request, response, next){
response = new CustomResponse(response)
response.send('baz') // this will print on the console the response and send it to the browser
})
感谢您的任何提示!
解决方案
这是你的中间件?
var CustomResponse = require('./customResponse') // the file above
server.use(function (req, response, next) {
response = new Response(response)
next()
})
对于此代码:
response = new Response(response)
我认为你应该像下面的代码一样使用它
response = new CustomResponse(response)
因为您使用的变量是CustomResponse
,不是Response
。
我希望它有帮助。
推荐阅读
- c# - 带有 SQLite 1.0.108.0 查询的实体框架 6 永远挂起
- db2 - 从 db2 中的日期字段中删除时间
- ios - 从 IOS Xamrin 本地调用 Rest API
- javascript - 在 Firefox 中将视频绘制到画布上很慢
- python - Python。从 Pandas 列中提取字符串的最后一位
- javascript - 在 electronjs 中使用视频标签时,.mkv 文件的字幕不显示
- python - 取一个张量的元素,它也在另一个张量中
- swift - iOS 12/Swift 强密码自动填充无法按预期工作
- codeigniter - 使用脚本时出错 $ this-> load-> library ('upload', $ config)
- javascript - 移动数组中元素的位置