Javascript 为Grunt connect服务器配置别名目录
我的源代码中有一些文件夹,我想通过grunt任务使用connect提供这些文件夹。我的文件夹结构如下Javascript 为Grunt connect服务器配置别名目录,javascript,node.js,gruntjs,connect,Javascript,Node.js,Gruntjs,Connect,我的源代码中有一些文件夹,我想通过grunt任务使用connect提供这些文件夹。我的文件夹结构如下 / /src 翡翠索引 /风格 main.css /距离 index.html /文件 index.html 我的grunt配置看起来像这样 grunt.initConfig({ connect: { options: { port: 8080, hostname: '0.0.0.0',
- /
- /src
- 翡翠索引
- /风格
- main.css
- /距离
- index.html
- /文件
- index.html
grunt.initConfig({
connect: {
options: {
port: 8080,
hostname: '0.0.0.0',
livereload: 35729
},
app: {
options: {
middleware: function (connect) {
return [
connect.static(require('path').resolve(pkg.paths.dist)),
connect.static(require('path').resolve(pkg.paths.src)),
connect.static(require('path').resolve(pkg.paths.docs))
];
}
}
},
}
})
启动服务器并访问http://localhost:8080/
将提供来自dist
的index.html
文件,该文件是从index.jade
编译而来的,它引用了main.css
,它是从src
尽职尽责地提供的。这一切都很棒,效果也很好
现在,我想从docs
访问index.html
文件,但要使用别名url,所以http://localhost:8080/mycustomurl
。我不想将我的文档放在子文件夹中,我只想配置connect以提供与docs
目录中的mycustomurl
匹配的URL
如何修改配置以实现此目的?使用自定义中间件<代码>中间件选项需要一个返回中间件数组的函数
custom_middleware: {
options: {
middleware: function(connect, options, middlewares) {
return [connect.static(require('path').resolve(pkg.paths.dist)),
connect.static(require('path').resolve(pkg.paths.src)),
function (req, res, next) {
if (req.url !== '/custom/url') {
next();
return;
}
// res.sendFile(pkg.paths.docs + '/index.html');
// you can access the "anything.html" by parsing the req.url
var file = req.url.split('/');
file = file[file.length-1];
res.sendFile(pkg.paths.docs + file);
}
];
}
}
}
有关更多配置选项,请参阅。谢谢您的回答,但我不想只提供新路由中的一个文件,我想代理任何与模式匹配的内容,以便从其他文件夹提供服务。什么,您是否尝试过我的解决方案,这不是提供一个文件,这里有三个中间件,第三个是对不同文件夹的代理,该文件夹匹配“/custom/url”模式@BillyMoonI希望对
/custom/url/anything.html
的请求被作为docs
文件夹中的文件anything.html
——并不总是提供index.html
@BillyMoon,这很简单,只需解析req.url
,请查看我的编辑,请注意,我还没有测试如何解析req.url
,它可能需要一些修复,请尝试适合自己。最后接受答案;)。我对你的答案投了赞成票,但仍然不满意——对不起。是否有办法在自定义函数中仍然使用connect.static
——以避免所有URL的手动解析、标题设置、加载文件等。。。所以,如果匹配自定义url,则使用自定义目录中的connect static提供服务,否则转到下一步。你能做到吗?