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.
CodePudding user response:
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);