2016-09-21 83 views
0

我有两条路线:app.use服务于静态文件。不同参数的ExpressJS路由

app.use('/test', earlyAccess(), express.static(path.join(__dirname, staticFolder))) 

app.get("/test", callback); 
app.get("/test/:id", callback); 

// Here is the callback 
var fileStream = fs.createReadStream(staticFolder + '/test.html'); 
fileStream.on('open', function() { 
    fileStream.pipe(res); 
}); 

从浏览器中,如果我拨打localhost:80/test/1 - 工作正常。 但如果我打电话localhost:80/test - 它会被重定向到主页面。在服务器控制台中,我收到了304条警告。

如何在expressjs中使用基于参数的路由?

+0

304仅指示文档未被修改。 '/ test'中的回调是做什么的? –

+0

加载HTML。 test /:id和/ test加载相同的html页面。 – user2325247

+0

你可以提供回调函数吗?! –

回答

-3

你可以尝试这样的:

app.use("/test/*", (req, res, next) => { 
    // your callback(req, res); 
    next(); 
}); 
app.get("/test/:id", callback); 

app.use,意味着你可以写一个中间件,它接下来会调用();

+0

而且,这是如何回答原始问题的? – jfriend00

+0

不是。它不起作用。 – user2325247

+0

这不适用于这个问题,它是泛化的路线。 –

0

尝试使用res.sendFile代替fs.createReadStream,是这样的:

res.sendFile('test.html'); 
+0

问题在于它不会触及/ test的回调。 – user2325247

+0

没有道理,除此之外还有更多路线?无论如何,res.sendFile比fs.createReadStream更好,用于返回文件。 –

+0

我不明白,你更多的路线是什么意思?/test或/ test/1应该为我加载html页面。 – user2325247

0

您可以检查回调中的请求参数,

在请求
app.get('/test', callback); 
app.get('/test/123', callback); 

// callback 
if(req.params.second) { 
    // code for route with param. - /test/123 
} 
else { 
// code for route without param. - /test 
} 

参数都存储在req.params为

{first:'NameOfRoute', second:'NextParam'} ... 

因此,在这里,

{first:'test', second:'123'} 
+0

我明白了。但它从来没有达到回调。 – user2325247