Express.js中res.send和res.json之间的区别

编程入门 行业动态 更新时间:2024-10-07 20:35:07
本文介绍了Express.js中res.send和res.json之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

res.send 和 res.json 之间的实际区别在于似乎执行相同的操作

What is actual difference between res.send and res.json as both seems to perform same operation of responding to client.

推荐答案

方法在传递对象或数组时是相同的,但 res.json ()还将转换非对象,例如 null 和 undefined 无效的JSON。

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.

该方法还使用 json replaceacer 和 json spaces 应用程序设置,因此您可以使用更多选项格式化JSON。这些选项设置如下:

The method also uses the json replacer and json spaces application settings, so you can format JSON with more options. Those options are set like so:

app.set('json spaces', 2); app.set('json replacer', replacer);

并传递给一个 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

这是发送方法没有的 res.json()方法中的代码有:

This is the code in the res.json() method that the send method doesn't have:

var app = this.app; var replacer = app.get('json replacer'); var spaces = app.get('json spaces'); var body = JSON.stringify(obj, replacer, spaces);

该方法最终作为 res.send()最后:

this.charset = this.charset || 'utf-8'; this.get('Content-Type') || this.set('Content-Type', 'application/json'); return this.send(body);

更多推荐

Express.js中res.send和res.json之间的区别

本文发布于:2023-11-25 06:23:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628658.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   js   Express   res   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!