当前位置: 首页 > 工具软件 > Express Map > 使用案例 >

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

公孙宏远
2023-12-01

本文翻译自:Proper way to return JSON using node or Express

So, one can attempt to fetch the following JSON object: 因此,可以尝试获取以下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"
}
$

Is there a way to produce exactly the same body in a response from a server using node or express? 有没有一种方法可以使用node或express在服务器的响应中生成完全相同的主体? Clearly, one can set the headers and indicate that the content-type of the response is going to be "application/json", but then there are different ways to write/send the object. 显然,可以设置标头并指示响应的内容类型将为“ application / json”,但是存在多种写入/发送对象的方式。 The one that I have seen commonly being used is by using a command of the form: 我经常看到的一种是通过使用以下形式的命令:

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

However, this has two points where one could argue as if they were "problems": 但是,这有两点可以使人争辩为“问题”:

  • We are sending a string. 我们正在发送一个字符串。
  • Moreover, there is no new line character in the end. 此外,最后没有换行符。

Another idea is to use the command: 另一个想法是使用命令:

response.send(anObject);

This appears to be sending a JSON object based on the output of curl similar to the first example above. 这似乎是基于curl的输出发送JSON对象,类似于上面的第一个示例。 However, there is no new line character in the end of the body when curl is again being used on a terminal. 但是,当在终端上再次使用curl时,在主体的末端没有换行符。 So, how can one actually write down something like this with a new line character appended in the end using node or node/express? 那么,如何使用node或node / express实际写下这样的内容并在末尾添加换行符呢?


#1楼

参考:https://stackoom.com/question/1KdtI/使用节点或Express返回JSON的正确方法


#2楼

That response is a string too, if you want to send the response prettified, for some awkward reason, you could use something like JSON.stringify(anObject, null, 3) 该响应也是一个字符串,如果您要发送经过修饰的响应,则出于某种尴尬的原因,可以使用JSON.stringify(anObject, null, 3)

It's important that you set the Content-Type header to application/json , too. 同样重要的是,还要将Content-Type标头设置为application/json

var http = require('http');

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

// > {"a":1}

Prettified: 美化:

var http = require('http');

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

// >  {
// >     "a": 1
// >  }

I'm not exactly sure why you want to terminate it with a newline, but you could just do JSON.stringify(...) + '\\n' to achieve that. 我不确定为什么要用换行符终止它,但是您可以执行JSON.stringify(...) + '\\n'来实现。

Express 表达

In express you can do this by changing the options instead . 在Express中,您可以通过更改选项来实现

'json replacer' JSON replacer callback, null by default 'json replacer' Replacer回调,默认为null

'json spaces' JSON response spaces for formatting, defaults to 2 in development, 0 in production 'json spaces'用于格式化'json spaces' JSON响应空间,开发中默认为2,生产中默认为0

Not actually recommended to set to 40 实际不建议设置为40

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

Then you could just respond with some json. 然后,您可以使用一些json进行响应。

res.json({ a: 1 });

It'll use the 'json spaces ' configuration to prettify it. 它将使用'json spaces ”配置进行美化。


#3楼

Since Express.js 3x the response object has a json() method which sets all the headers correctly for you and returns the response in JSON format. 从Express.js 3x开始,响应对象具有json()方法,该方法可以为您正确设置所有标头,并以JSON格式返回响应。

Example: 例:

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

#4楼

If you are trying to send a json file you can use streams 如果您尝试发送json文件,则可以使用流

var usersFilePath = path.join(__dirname, 'users.min.json');

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

#5楼

You can just prettify it using pipe and one of many processor. 您可以使用管道和众多处理器之一对其进行美化。 Your app should always response with as small load as possible. 您的应用应始终以尽可能小的负载进行响应。

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

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


#6楼

You can use a middleware to set the default Content-Type, and set Content-Type differently for particular APIs. 您可以使用中间件来设置默认的Content-Type,并为特定的API设置不同的Content-Type。 Here is an example: 这是一个例子:

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>`);
})
 类似资料: