【问题标题】:how to publish a page using node.js如何使用 node.js 发布页面
【发布时间】:2015-04-08 15:39:20
【问题描述】:

我刚刚开始学习 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');

但是在使用视图时我该怎么做呢。

【问题讨论】:

  • 这是mongodb和express吧?
  • 它是 express 和 nedb,这是我在 github 上找到的一个扁平的 NoSQL 存储 - 他们的 github 页面确实说它是 Mongo 的一个子集

标签: node.js asynchronous express nedb


【解决方案1】:

只要得到必要的数据,只需send 回复即可!您不需要在路由中直接使用endsend,但也可以在嵌套回调中进行:

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());
    });
});

我还包括使用res.type 发送正确的Content-Type

另外:不要忘记添加正确的错误处理。例如,如果在检索文档时发生错误,您可以使用 res.sendStatus(500)

【讨论】:

  • 啊,这很简单。我没有考虑到这一点。我还在习惯异步回调方法。我最后一次编写通用应用程序是在 .net 2.0 天!
猜你喜欢
  • 2012-03-02
  • 1970-01-01
  • 2016-02-10
  • 2016-09-29
  • 2012-11-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
相关资源
最近更新 更多