[英]Unexpected token in express ratelimit message
I'm using the package express-rate-limit
to limit my express API requests.我正在使用 package
express-rate-limit
来限制我的 express API 请求。 I'm using Pug for my client.我正在为我的客户使用 Pug。 Everything works fine, but whenever the ratelimit is triggered, I get the expected
POST: 429
error, but then this error:一切正常,但每当触发速率限制时,我都会收到预期的
POST: 429
错误,然后出现此错误:
Uncaught (in promise) SyntaxError: Unexpected token 'Y', "You can li"... is not valid JSON
未捕获(承诺)SyntaxError:意外标记“Y”,“你可以”......无效 JSON
This is in relation to by express ratelimit message
parameter:这与 by express ratelimit
message
参数有关:
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.当我们以字符串格式发送请求或以字符串格式服务器发送期望 JSON 字符串的响应时,就会出现这种错误。
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默认情况下我们也可以设置响应 header JSON
res.setHeader('Content-Type', 'application/json');
or another way I think we can solve this problem send JSON output to the server或者我认为我们可以解决这个问题的另一种方式发送 JSON output 到服务器
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.