3

How do I send data from server to the client using nodejs?

So basically I call this function by clicking a button

javascript

function createStuff(tid) {
    $.ajax({
        type: "POST",
        url: '/create/',
        data: {tid: tid}
        success: function(id) {
            doStuff(id);
        },
        error: function(jqXHR, textstatus, errorThrown) {
            alert('text status ' + textstatus + ', err ' + errorThrown);
        }
    });
};

This then handles the request

server

exports.create = function(req, res) {
    new Stuff({
        content: "random stuff"
    }).save(function(err, stuff) {
        Otherstuff.update({_id: req.body.tid}, {$push: {stuffes: stuff}}, {upsert: true}, function(err, mvar) {
            res.redirect(301, '/' + req.body.tid);
        });
    });
};

But I need to send along the newly created stuff._id with the res.redirect. The thing is I don't want to send it as res.redirect(301, '/' + req.body.tid + '/' + stuff._id) because I would have to do a whole new router which doesn't seem flexible. Also, when I do this request, the web page doesn't reload, which is just like I want it.

I tried using res.send(stuff._id), but I could only do it once (because the connection closes after it it seems). I'm using the following libraries: mongoose, jquery, express

4

1 回答 1

7

如果我理解正确,您想用您在请求中获得的原始 id 以及新生成的 id 回复客户端。我不明白的是,redirect如果你不想重新加载任何页面,你为什么要使用?

你可以简单地,

var obj = {
    tid: req.body.tid,
    _id: stuff._id
};

res.send(JSON.stringify(obj));

而且,ajax成功处理程序将是

success: function(data) {
    var obj = JSON.parse(data);
    var id = obj._id;
    doStuff(id);
}

我想这就是你想要的。

编辑:

正如 deitch 所指出的,express它本身将对象转换为 JSON 字符串,并Content-Type为 JQuery 添加一个标头以正确识别字符串并将其解析为 JSON 对象。所以不需要stringifyparse数据。

于 2013-08-12T12:35:41.237 回答