Goj*_*e87 29 meteor meteorite iron-router
我刚开始在流星上使用铁路由器.我需要在主页上显示图像.我能够使用客户端路由为'home'配置路由.对于我尝试google的静态文件,发现添加服务器端路由可能有所帮助.所以,我在服务器的router.js上添加了以下代码.
Router.map(function() {
this.route('files', {
path: '/files/:path(*)',
action: function() {
var path = this.params.path;
console.log('will serve static content @ '+path);
this.response.sendfile(path);
}
});
});
Run Code Online (Sandbox Code Playgroud)
当我尝试访问时http://localhost:3000/files/someImage.png,它表示没有定义路由/files/someImage.png.难道我做错了什么?有没有其他方法使用铁路由器提供静态文件?
Dav*_*don 61
您可以将文件放在public目录下,而不是完成所有这些操作.如果添加文件:
myApp/public/images/kitten.png
Run Code Online (Sandbox Code Playgroud)
您可以从以下模板访问它:
<img src="/images/kitten.png">
Run Code Online (Sandbox Code Playgroud)
不需要任何路线来完成这项工作.
小心忽视铅斜线.
<img src="images/kitten.png">
Run Code Online (Sandbox Code Playgroud)
上面的示例将适用于您的顶级路线,如/ books,这使得它很容易错过,但在/ books/pages上失败.
您可能只需要确保路由位于客户端和服务器上可见的公共区域(此路由实际上在服务器上运行)并指定where: 'server'.另外我们需要从磁盘加载实际文件,这意味着我们需要服务器上的实际路径到文件,我们需要加载'fs'.
var fs = Npm.require('fs');
Router.map(function() {
this.route('files', {
path: '/files/:path(*)',
where: 'server',
action: function() {
var path = this.params.path;
var basedir = '~/app/';
console.log('will serve static content @ '+ path);
var file = fs.readFileSync(basedir + path);
var headers = {
'Content-type': 'image/png',
'Content-Disposition': "attachment; filename=" + path
};
this.response.writeHead(200, headers);
return this.response.end(file);
}
});
});
Run Code Online (Sandbox Code Playgroud)
几个注意事项:您应该将实际的下载代码移动到仅服务器的函数中,然后调用它,将响应传递给函数.
您还应该对路径进行一些验证,这样您就不会允许任何人随意下载服务器上的文件.
此外,这是明确设置内容类型,您可能希望对图像执行此操作,但可能不会为其他内容类型设置.对于通用类型,您可以将其设置为application/octet-stream
当然,如前所述,如果您的唯一目标是在部署时提供一些静态内容,那么您应该只使用该/public目录.
| 归档时间: |
|
| 查看次数: |
26677 次 |
| 最近记录: |