node.js res.json搞砸了

时间:2014-04-23 21:14:49

标签: javascript node.js mongodb mongoose

首先我发出'/ init'请求,响应为{"x":50}, 然后我发出'/ user'请求,响应为{"x":50,"data":"jack"}。到目前为止没问题,但如果我再次发出初始请求,它会再次发出{"x":50,"data":"jack"}响应,这怎么可能?

    var resp.success = {"x":50} 

    exports.init = function (req, res) {
        res.json(resp.success)
    };

    exports.user = function (req, res) {
        User.findOne({_id: "1234"}).exec(function (err, user) {
            var response = resp.success;
            response.data = user.name;
            res.json(response);
        });
    };

1 个答案:

答案 0 :(得分:2)

因为你在@init和@user方法之外的作用域中定义了var resp.success = {" x":50},所以从内部修改/读取resp.success这些方法,他们正在访问resp.success的单个共享对象实例。您可以通过在@init方法和@user:

中单独定义resp.success来解决此问题
exports.init = function (req, res) { 
    var resp.success = {"x":50} 
    res.json(resp.success)
};

exports.user = function (req, res) {
    var resp.success = {"x":50} 
    User.findOne({_id: "1234"}).exec(function (err, user) {
        var response = resp.success;
        response.data = user.name;
        res.json(response);
    });
};

如果你使用underscoreJS库,你也可以这样做:

var resp.success = {"x":50} 
exports.init = function (req, res) { 
    var successResponseForThisRequest = _.clone(res.success);
    res.json(resp.success)
};

exports.user = function (req, res) {
    User.findOne({_id: "1234"}).exec(function (err, user) {
        var successResponseForThisRequest = _.clone(res.success);
        response.data = user.name;
        res.json(response);
    });
};