TypeError: Cannot read property 'ip' of undefined - express-rate-limit

4347 views javascript

I use express-rate-limit package in the below code:

const express = require('express');
const router = express.Router();
const RateLimit = require('express-rate-limit');
const cors = require('cors')

const apiLimiter = new RateLimit({
    windowMs: 1000 * 60 * 5,
    max: 5,
    // message : "??????? ??? ???? ???? ???? 15 ????? ???? ?????? ???? ????"
    handler: function (req, res, /*next*/) {
            data: '??????? ??? ???? ???? ???? 15 ????? ???? ?????? ???? ????',
            status: 'error'

let prefixes = ["v1"];
for (let prefix of prefixes) {
    router.use(`/${prefix}/`, cors(), apiLimiter(), require(`./${prefix}/home`));
    router.use(`/${prefix}/auth`, cors(), apiLimiter(), require(`./${prefix}/auth`));
    router.use(`/${prefix}/admin`, cors(), apiLimiter(), require(`./${prefix}/admin`));

module.exports = router;

Before I use this, everything works fine. But after using this package and when I start my project, I get below error:

    [nodemon] restarting due to changes...
[nodemon] starting `node server.js`
C:\Users\Sayyid Ali\Desktop\gheymat\node_modules\express-rate-limit\lib\express-rate-limit.js:16
      return req.ip;

TypeError: Cannot read property 'ip' of undefined
    at Object.keyGenerator (C:\Users\Sayyid Ali\Desktop\gheymat\node_modules\express-rate-limit\lib\express-rate-limit.js:16:18)
    at rateLimit (C:\Users\Sayyid Ali\Desktop\gheymat\node_modules\express-rate-limit\lib\express-rate-limit.js:54:25)
    at Object.<anonymous> (C:\Users\Sayyid Ali\Desktop\gheymat\app\routes\index.js:20:39)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Application.setRouters (C:\Users\Sayyid Ali\Desktop\gheymat\app\index.js:35:17)
    at new Application (C:\Users\Sayyid Ali\Desktop\gheymat\app\index.js:13:14)
    at Object.<anonymous> (C:\Users\Sayyid Ali\Desktop\gheymat\server.js:4:1)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
[nodemon] app crashed - waiting for file changes before starting...

How can I handle this? Please help me!

answered question

1 Answer


I think you should use it like this

router.use(`/${prefix}/`, cors(), apiLimiter, require(`./${prefix}/home`));

posted this

Have an answer?


Please login first before posting an answer.