响应JSON对象还是JSON.stringify? [英] Response JSON object or JSON.stringify?

查看:187
本文介绍了响应JSON对象还是JSON.stringify?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要返回JSON内容

Suppose I want to return JSON content

var content = {
  a: 'foo',
  b: 'bar'
};

返回JSON数据的最佳实践是什么?

What is the best practice to return my JSON data?

A)返回对象原样;即res.end(content)?

A) Return object as is; i.e res.end(content)?

B)JSON.stringify(content),然后在客户端上调用JSON.parse(content)?

B) JSON.stringify(content) and then call JSON.parse(content) on the client?

推荐答案

如果使用express的res.json发送响应,则可以直接将对象作为application/json编码的响应发送.

If you send the response with express's res.json you can send the Object directly as application/json encoded response.

app.get('/route/to/ressource', function(req, res){
  var oMyOBject = {any:'data'};

   res.json(oMyOBject);
});

这篇关于响应JSON对象还是JSON.stringify?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆