首页 文章

使用node或Express返回JSON的正确方法

提问于
浏览
304

因此,可以尝试获取以下JSON对象:

$ curl -i -X GET http://echo.jsontest.com/key/value/anotherKey/anotherValue
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=ISO-8859-1
Date: Wed, 30 Oct 2013 22:19:10 GMT
Server: Google Frontend
Cache-Control: private
Alternate-Protocol: 80:quic,80:quic
Transfer-Encoding: chunked

{
   "anotherKey": "anotherValue",
   "key": "value"
}
$

有没有办法在使用node或express的服务器的响应中生成完全相同的主体?显然,可以设置标头并指示响应的内容类型将是“application / json”,但是有不同的方式来编写/发送对象 . 我经常使用的那个是使用以下形式的命令:

response.write(JSON.stringify(anObject));

然而,这有两点可以说是好像是“问题”:

  • 我们正在发送一个字符串 .

  • 此外,最后没有换行符 .

另一个想法是使用命令:

response.send(anObject);

这似乎是基于curl的输出发送一个JSON对象,类似于上面的第一个例子 . 但是,当在终端上再次使用卷曲时,在身体的末端没有新的线条字符 . 那么,如何使用node或node / express在最后添加一个新行字符来实际写下这样的东西?

6 回答

  • 1

    您可以使用中间件来设置默认的Content-Type,并为特定的API设置不同的Content-Type . 这是一个例子:

    const express = require('express');
    const app = express();
    
    const port = process.env.PORT || 3000;
    
    const server = app.listen(port);
    
    server.timeout = 1000 * 60 * 10; // 10 minutes
    
    // Use middleware to set the default Content-Type
    app.use(function (req, res, next) {
        res.header('Content-Type', 'application/json');
        next();
    });
    
    app.get('/api/endpoint1', (req, res) => {
        res.send(JSON.stringify({value: 1}));
    })
    
    app.get('/api/endpoint2', (req, res) => {
        // Set Content-Type differently for this particular API
        res.set({'Content-Type': 'application/xml'});
        res.send(`<note>
            <to>Tove</to>
            <from>Jani</from>
            <heading>Reminder</heading>
            <body>Don't forget me this weekend!</body>
            </note>`);
    })
    
  • 0

    早期版本的Express使用 app.use(express.json())bodyParser.json() read more about bodyParser middleware

    在最新版本的快递我们可以简单地使用 res.json()

    const express = require('express'),
        port = process.env.port || 3000,
        app = express()
    
    app.get('/', (req, res) => res.json({key: "value"}))
    
    app.listen(port, () => console.log(`Server start at ${port}`))
    
  • 16

    从Express.js 3x开始,响应对象有一个json()方法,它为您正确设置所有标头并以JSON格式返回响应 .

    例:

    res.json({"foo": "bar"});
    
  • 317

    你可以用管道和许多处理器中的一个来美化它 . 您的应用应始终以尽可能小的负载响应 .

    $ curl -i -X GET http://echo.jsontest.com/key/value/anotherKey/anotherValue | underscore print
    

    https://github.com/ddopson/underscore-cli

  • 4

    该响应也是一个字符串,如果你想发送反应美化,出于某些尴尬的原因,你可以使用像 JSON.stringify(anObject, null, 3) 这样的东西

    Content-Type 标头设置为 application/json 也很重要 .

    var http = require('http');
    
    var app = http.createServer(function(req,res){
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify({ a: 1 }));
    });
    app.listen(3000);
    
    // > {"a":1}
    

    美化:

    var http = require('http');
    
    var app = http.createServer(function(req,res){
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify({ a: 1 }, null, 3));
    });
    app.listen(3000);
    
    // >  {
    // >     "a": 1
    // >  }
    

    我不确定你为什么要用换行符来终止它,但是你可以做 JSON.stringify(...) + '\n' 来实现它 .

    快递

    在快递中,您可以通过changing the options instead执行此操作 .

    'json replacer'JSON替换器回调,默认情况下为null'json spaces'用于格式化的JSON响应空间,默认为开发中的2, 生产环境 中为0

    实际上并不建议设置为40

    app.set('json spaces', 40);
    

    然后你可以回答一些json .

    res.json({ a: 1 });
    

    它将使用 'json spaces '配置来美化它 .

  • 455

    如果您尝试发送json文件,则可以使用流

    var usersFilePath = path.join(__dirname, 'users.min.json');
    
    apiRouter.get('/users', function(req, res){
        var readable = fs.createReadStream(usersFilePath);
        readable.pipe(res);
    });
    

相关问题