我才刚刚开始学习node.js。在过去的两天里,我一直在研究一个接受用户输入并发布ICS文件的项目。我有所有的工作。现在考虑何时必须显示此数据。我得到一个router.get
看看我是否在/cal
页面上..
router.get('/cal', function(req, res, next)
{
var db = req.db;
var ical = new icalendar.iCalendar();
db.find({
evauthor: 'mykey'
}, function(err, docs) {
docs.forEach(function(obj) {
var event2 = ical.addComponent('VEVENT');
event2.setSummary(obj.evics.evtitle);
event2.setDate(new Date(obj.evics.evdatestart), new Date(obj.evics.evdateend));
event2.setLocation(obj.evics.evlocation)
//console.log(ical.toString());
});
});
res.send(ical.toString());
// res.render('index', {
// title: 'Cal View'
// })
})
因此,当/cal
被请求时,它将遍历我的数据库并创建ICS日历ical
。如果我console.log(ical.toString)
在循环中执行此操作,则会按照协议为我提供格式正确的日历。
但是,我想以此结束响应。最后,我res.send
只是看看页面上发布了什么。这就是被发表的东西
BEGIN:VCALENDAR VERSION:2.0
PRODID:calendar//EN
END:VCALENDAR
现在的原因很明显。它是node.js的本质。在回调函数完成将每个人添加VEVENT
到日历对象之前,响应已发送到浏览器。
我有两个相关的问题:
1)“等待”直到回调完成的正确方法是什么?
2)如何使用res
.ics动态链接发送ical.toString()
内容。我需要为此创建一个新视图吗?
编辑:我想为2我必须像这样设置HTTP标头
//set correct content-type-header
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename=calendar.ics');
但是在使用视图时我该怎么做。
send
一旦获得必要的数据,仅需响应!您不需要end
或send
直接在路线中,但也可以在嵌套回调中进行操作:
router.get('/cal', function(req, res, next) {
var db = req.db;
var ical = new icalendar.iCalendar();
db.find({
evauthor: 'mykey'
}, function(err, docs) {
docs.forEach(function(obj) {
var event2 = ical.addComponent('VEVENT');
event2.setSummary(obj.evics.evtitle);
event2.setDate(new Date(obj.evics.evdatestart), new Date(obj.evics.evdateend));
event2.setLocation(obj.evics.evlocation)
});
res.type('ics');
res.send(ical.toString());
});
});
我还包括使用发送适当Content-Type
的信息res.type
。
另外:不要忘记添加适当的错误处理。例如,res.sendStatus(500)
如果在检索文档时发生错误,则可以使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句