问题描述
我想在Express.js的响应对象中添加一个body
属性,该属性将在每次send method is called
时调用,我通过添加以下代码作为中间件来做到这一点,
I would like to add a body
property to Express.js' response object, which will be called every time the send method is called
,I do it by adding the following code as a middleware,
但由于某种原因,当我调用res.send
时,此函数被调用两次(一次是body为object,第二次是同一对象,而是字符串)1.为什么叫两次?2.为什么以及何时将其转换为字符串?
but for some reason, when I call res.send
this function is called twice (once when body is object and in the 2nd time the same object butas a string )1.why is it being called twice?2.why and when is it being converted to string?
applicationsRouter.use(function (req, res, next) {
var send = res.send;
res.send = function (body) {
res.body = body
send.call(this, body);
};
next();
});
推荐答案
您可能正在使用类似这样的东西:
You are probably using something like this:
res.send({ foo : 'bar' });
换句话说,您要将对象传递给res.send
.
In other words, you're passing an object to res.send
.
这将执行以下操作:
- 使用对象作为参数调用
res.send
-
res.send
检查参数类型,然后看到它是一个对象,并将其传递给res.json
-
res.json
将对象转换为JSON字符串,然后再次调用res.send
,但这一次使用JSON字符串作为参数
- call
res.send
with the object as argument res.send
checks the argument type and sees that it's an object, which it passed tores.json
res.json
converts the object to a JSON string, and callsres.send
again, but this time with the JSON string as argument
这篇关于Express.js-添加响应主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!