[英]node.js res.json messed up
first i make a '/init' request and the response is {"x":50}
, then i make a '/user' request and the response is {"x":50,"data":"jack"}
. 首先我发出'/ init'请求,响应是{"x":50}
,然后我发出'/ user'请求,响应是{"x":50,"data":"jack"}
。 No problem so far, but if i make an init request again it makes a {"x":50,"data":"jack"}
response again, how is this possible? 到目前为止没问题,但是如果我再次发出初始请求,它会再次发出{"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);
});
};
Because you've defined var resp.success = {"x":50} in a scope outside the @init and @user methods, when you modify/read the resp.success from within those methods, they are accessing a single shared object instance of resp.success. 因为您已在@init和@user方法之外的作用域中定义了var resp.success = {“x”:50},所以当您从这些方法中修改/读取resp.success时,它们正在访问单个共享对象resp.success的实例。 You can fix this by defining resp.success independently inside the @init method and @user: 您可以通过在@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);
});
};
If you use the underscoreJS library, you could also do something like this: 如果你使用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);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.