Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

javascript - Express.js中res.send和res.json之间的区别(Difference between res.send and res.json in Express.js)

res.sendres.json之间的实际区别是什么,因为两者似乎都执行响应客户端的相同操作。

  ask by ram translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The methods are identical when an object or array is passed, but res.json() will also convert non-objects, such as null and undefined , which are not valid JSON.(传递对象或数组时,方法是相同的,但res.json()也将转换非对象,例如nullundefined ,这些对象是无效的JSON。)

The method also uses the json replacer and json spaces application settings, so you can format JSON with more options.(该方法还使用json replacerjson spaces应用程序设置,因此您可以使用更多选项格式化JSON。) Those options are set like so:(这些选项设置如下:) app.set('json spaces', 2); app.set('json replacer', replacer); And passed to a JSON.stringify() like so:(并传递给JSON.stringify()如下所示:) JSON.stringify(value, replacer, spacing); // value: object to format // replacer: rules for transforming properties encountered during stringifying // spacing: the number of spaces for indentation This is the code in the res.json() method that the send method doesn't have:(这是send方法没有的res.json()方法中的代码:) var app = this.app; var replacer = app.get('json replacer'); var spaces = app.get('json spaces'); var body = JSON.stringify(obj, replacer, spaces); The method ends up as a res.send() in the end:(该方法最终以res.send()结尾:) this.charset = this.charset || 'utf-8'; this.get('Content-Type') || this.set('Content-Type', 'application/json'); return this.send(body);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...