简体   繁体   中英

Unexpected token in express ratelimit message

I'm using the package express-rate-limit to limit my express API requests. I'm using Pug for my client. Everything works fine, but whenever the ratelimit is triggered, I get the expected POST: 429 error, but then this error:

Uncaught (in promise) SyntaxError: Unexpected token 'Y', "You can li"... is not valid JSON

This is in relation to by express ratelimit message parameter:

const addLikeLimiter = rateLimit({
    windowMs: 1000, // 1 second
    max: 1, //Limit 1 like per one second
    message: 'You can like once per second.',
    standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
    legacyHeaders: false, // Disable the `X-RateLimit-*` headers
})

app.use('/api/like', addLikeLimiter)

Is there any way I can fix this? I'm not sure why I'm getting this error.

This kind of error will come when we send a request in string format or send a response in string format server expecting a JSON string.

while sending the request body to the express server we will use

app.use(express.json()) //if its not there add this one 

by default also we can set the response header JSON

res.setHeader('Content-Type', 'application/json');

or another way I think we can solve this problem send JSON output to the server

  const addLikeLimiter = rateLimit({
  windowMs: 1000,
  max: 1,
  standardHeaders: true,
  legacyHeaders: false,
  handler: function (req, res /*next*/) {
    return res.status(429).json({
      error: 'You sent too many requests. Please wait a while then try again',
    });
  },
});

app.use('/api/like', addLikeLimiter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM