节点并表达发送格式化的json [英] node and express send json formatted

查看:66
本文介绍了节点并表达发送格式化的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过express发送格式化的json.

I'm trying to send formatted json with express.

这是我的代码:

var app = express();

app.get('/', function (req, res) {
  users.find({}).toArray(function(err, results){
    // I have try both
    res.send(JSON.stringify(results, null, 4));
    // OR
    res.json(results);
  });
});

我在浏览器中获取了json,但这是一个字符串.如何发送它以便它在浏览器中可读?

I get the json in my browser but it's a string. How can I send it so it's readable in the browser?

推荐答案

您将必须像这样将Content-Type设置为application/json

You're going to have to set the Content-Type to application/json like this

app.get('/', function (req, res) {
    users.find({}).toArray(function(err, results){
        res.header("Content-Type",'application/json');
        res.send(JSON.stringify(results, null, 4));
  });
});

这篇关于节点并表达发送格式化的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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