xyz*_*242 5 middleware node.js express
在我的应用程序中,我希望能够捕获由express-rate-limit 包生成的消息。这是我的代码示例。我希望能够使用中间件捕获消息部分,以便我可以对其进行后处理(在本例中我有多种语言)。
const apiCreatingAccountLimiter = rateLimit({
windowMs: 10 * 60 * 1000, // 10 minutes
max: 10, // limit each IP to 10 requests per windowMs
message: {
limiter: true,
type: "error",
message: 'maximum_accounts'
}
});
Run Code Online (Sandbox Code Playgroud)
进而
router.post('/signup', apiCreatingAccountLimiter, (req, res, next) => {
// handling the post request
})
Run Code Online (Sandbox Code Playgroud)
我为其他一些 API 消息设置了类似的解决方案中间件:
// error processing middleware
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
res.status(statusCode).send({
type: 'error',
message: err.message,
fields: err.fields === '' ? '' : err.fields,
code: err.code === '' ? '' : err.code,
section: err.section === '' ? 'general' : err.section
});
});
Run Code Online (Sandbox Code Playgroud)
然而,当尝试从express-rate-limit包中读取消息时,它似乎根本没有通过这个中间件传递。我猜这是因为它发生在它到达任何 API 并触发这个中间件之前。
查看经过的 res 部分,我可以看到有一个包含以下数据的对象:
rateLimit:
{ limit: 10,
current: 10,
remaining: 0,
resetTime: 2019-10-21T12:35:46.919Z
},
Run Code Online (Sandbox Code Playgroud)
但这似乎并没有传输 apiCreatingAccountLimiter 中最顶部设置的消息对象。我想知道我怎样才能到达它?
有谁知道如何做到这一点?我不希望这些消息在前端被翻译。我需要在 NodeJS 服务器上进行翻译。我只对中间件部分感兴趣,我可以在其中捕获消息并对其进行后处理。
在阅读源代码时,您应该使用处理程序选项作为选项,而不是使用其他中间件。
const apiCreatingAccountLimiter = rateLimit({
windowMs: 10 * 60 * 1000, // 10 minutes
max: 10, // limit each IP to 10 requests per windowMs
message: "my initial message",
handler: function(req, res /*, next*/) {
var myCustomMessage = require('anotherModuleYouWannaUse_ForExemple');
res.status(options.statusCode).send(myCustomMessage);
},
});
Run Code Online (Sandbox Code Playgroud)
最后,您将找到源代码的摘录
function RateLimit(options) {
options = Object.assign(
{
windowMs: 60 * 1000, // milliseconds - how long to keep records of requests in memory
max: 5, // max number of recent connections during `window` milliseconds before sending a 429 response
message: "Too many requests, please try again later.",
statusCode: 429, // 429 status = Too Many Requests (RFC 6585)
headers: true, //Send custom rate limit header with limit and remaining
skipFailedRequests: false, // Do not count failed requests (status >= 400)
skipSuccessfulRequests: false, // Do not count successful requests (status < 400)
// allows to create custom keys (by default user IP is used)
keyGenerator: function(req /*, res*/) {
return req.ip;
},
skip: function(/*req, res*/) {
return false;
},
handler: function(req, res /*, next*/) {
res.status(options.statusCode).send(options.message);
},
onLimitReached: function(/*req, res, optionsUsed*/) {}
},
options
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9120 次 |
| 最近记录: |