[英]Expressjs multiple optional parameters trigger request handler twice
Hello I need a second pair of eyes because I'm not sure why this is happening... I want to create 1 request handler which might accept 0 or 1 or 2 parameters eg: http://hocalhost:3000/{seed}/{size}
, seed
and size
parameters must be optional.您好,我需要第二双眼睛,因为我不确定为什么会这样……我想创建 1 个可能接受 0 或 1 或 2 个参数的请求处理程序,例如:
http://hocalhost:3000/{seed}/{size}
, seed
和size
参数必须是可选的。
However the below example doesn't work and the console.log
is being printed twice.但是,下面的示例不起作用,并且
console.log
被打印了两次。 This doesn't happen if I change the handlers route to /api/:seed?/:size?
如果我将处理程序路由更改为
/api/:seed?/:size?
. . Why is this happening & what am I doing wrong?
为什么会发生这种情况&我做错了什么?
const sharp = require('sharp');
const express = require('express');
const settings = require('./settings');
const app = express();
const calculateDensity = (s) => {
return (72 * s) / 180;
}
app.get('/:seed?/:size?', (req, res) => {
console.log('Why am I seeing this log?');
res.end();
})
app.listen(settings.PORT, () => {
console.log(`Example app listening at http://localhost:${settings.PORT}`)
})
So this is your default route所以这是你的默认路线
app.get('/:seed?/:size?', (req, res) => {
console.log('Why am I seeing this log?');
res.end();
})
Lets have another route让我们有另一条路线
app.get('/test', (req, res) => {
console.log('Test called');
res.end();
})
Now on browser localhost:port/test
Now which route will call.现在在浏览器上
localhost:port/test
现在将调用哪个路由。 As per your code it will consider that you are calling default route, where your first two argument is optioal.根据您的代码,它会认为您正在调用默认路由,其中您的前两个参数是可选的。
So always default route will called.所以总是会调用默认路由。 and test route skipped.
并跳过了测试路线。 Because
test
is now parameter of default
route.因为
test
现在是default
路由的参数。 Not another route不是另一条路线
Think deeply Either test route work or default route
深入思考 测试路由工作还是默认路由
Browser automatically called favicon.ico
after load.加载后浏览器自动调用
favicon.ico
。 it load twice for favicon.ico
and the route we define.它为
favicon.ico
和我们定义的路线加载了两次。
We can resolve it like below code我们可以像下面的代码一样解决它
app.get('/favicon.ico', (req, res) => {
res.end()
})
app.get('/:seed?/:size', (req, res) => {
console.log(req.url)
if (req.url !== "/favicon.ico") {
console.log('Why am I seeing this log?');
}
res.end();
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.