节点快递中的静态路由 [英] Static routing in node express
问题描述
我在Node Express中使用了一组静态路由,并且遇到一种非常奇怪的现象.
Im using a set of static routes in Node Express and are experiencing a very strange phenomenon.
设置路由,以便'/list/*'
和'/setup/*'
到达不同的html文件,在这些文件中使用了目录作为存储ID,例如在 url/setup/12345
页面上更新信息会将信息存储在 12345
中.
The routing is set up so that '/list/*'
and '/setup/*'
gets to different html-files where the directories are used kind of as storage id, for example updating info on the page url/setup/12345
would store info in 12345
.
为了能够加载脚本,还存在带有正则表达式匹配/assets/
的路由,以允许访问 url/setup/assets/script.js
而无需路由到具有新存储ID的 setup.html
.
To be able to load scripts and such there is also route with regex matching /assets/
to allow url/setup/assets/script.js
to be reached without routing to setup.html
with a new storage id.
我的问题是,即使它们具有相同的功能,它也适用于 url/setup/assets/script.js
,但不适用于 url/list/assets/script.js
路由.
My problem is that this works for url/setup/assets/script.js
but not for url/list/assets/script.js
even though they have identical routings.
导航到 url/list/assets/script.js
会导致 list.html
(不需要的行为)
Navigating to url/list/assets/script.js
leads to list.html
(unwanted behaviour)
导航到 url/setup/assets/script.js
会导致 script.js
(有害行为)
Navigating to url/setup/assets/script.js
leads to script.js
(wanted behaviour)
关于'/list/*'`为什么行不通的任何想法?
Any ideas on why '/list/*'` wont work?
这是我的静态路线:
app.use(/assets/, express.static(wwwPath));
app.use('/list/*', function(req, res, next) {
res.sendFile('list.html', { root: wwwPath });
});
app.use('/setup/*', function(req, res, next) {
res.sendFile('setup.html', { root: wwwPath });
});
推荐答案
解决方案是使用自定义中间件.这是新路线:
The solution was to use custom middleware. Here are the new routes:
var requestParser = function(req, res, next) {
if(req.originalUrl.indexOf('/assets/') >= 0) {
var assetPath = path.join(wwwPath, req.path.slice(req.url.indexOf('/assets/')));
fs.stat(assetPath, function(error, stat){
if(stat && stat.isFile()) {
res.sendFile(assetPath);
}
else{
res.status(404).send('<h1>404</h1>');
}
});
}
else {
next();
}
};
app.use(requestParser);
app.use('/list/*', function(req, res, next) {
res.sendFile('schema.html', { root: wwwPath });
});
app.use('/setup/*', function(req, res, next) {
res.sendFile('setup.html', { root: wwwPath });
});
这篇关于节点快递中的静态路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!