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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19696240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:08:37  来源:igfitidea点击:

Proper way to return JSON using node or Express

jsonnode.jsexpresshttpresponse

提问by MightyMouse

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? 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. The one that I have seen commonly being used is by using a command of the form:

有没有办法在使用 node 或 express 的服务器的响应中生成完全相同的正文?显然,可以设置标题并指示响应的内容类型将是“application/json”,但是有不同的方式来写入/发送对象。我看到常用的一种是使用以下形式的命令:

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. However, there is no new line character in the end of the body when curl is again being used on a terminal. So, how can one actually write down something like this with a new line character appended in the end using node or node/express?

这似乎是基于 curl 的输出发送一个 JSON 对象,类似于上面的第一个示例。但是,当 curl 再次在终端上使用时,正文末尾没有换行符。那么,如何使用 node 或 node/express 在末尾附加一个换行符来实际写下这样的东西呢?

回答by bevacqua

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-Typeheader 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 spaces'JSON response spaces for formatting, defaults to 2 in development, 0 in production

'json replacer'JSON 替换回调,默认为 null

'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' 配置来美化它。

回答by JamieL

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"});

回答by Connor Leech

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);
});

回答by vkarpov15

The res.json()functionshould be sufficient for most cases.

对于大多数情况,该res.json()功能应该足够了。

app.get('/', (req, res) => res.json({ answer: 42 }));

The res.json()function converts the parameter you pass to JSON using JSON.stringify()and sets the Content-Typeheaderto application/json; charset=utf-8so HTTP clients know to automatically parse the response.

res.json()函数使用将您传递给 JSON 的参数转换为 JSON JSON.stringify()并将Content-Type标头设置application/json; charset=utf-8以便 HTTP 客户端知道自动解析响应。

回答by IXOVER

if u're using Express u can use this:

如果你使用 Express 你可以使用这个:

res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({key:"value"}));

or just this

或者只是这个

res.json({key:"value"});

回答by pawelzny

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

回答by Nishant

You can make a helper for that: Make a helper function so that you can use it everywhere in your application

您可以为此创建一个帮助程序:创建一个帮助程序功能,以便您可以在应用程序的任何地方使用它

function getStandardResponse(status,message,data){
    return {
        status: status,
        message : message,
        data : data
     }
}

Here is my topic route where I am trying to get all topics

这是我的主题路线,我试图在其中获取所有主题

router.get('/', async (req, res) => {
    const topics = await Topic.find().sort('name');
    return res.json(getStandardResponse(true, "", topics));
});

Response we get

我们得到的回应

{
"status": true,
"message": "",
"data": [
    {
        "description": "sqswqswqs",
        "timestamp": "2019-11-29T12:46:21.633Z",
        "_id": "5de1131d8f7be5395080f7b9",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575031579309.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": "sqswqswqs",
        "timestamp": "2019-11-29T12:50:35.627Z",
        "_id": "5de1141bc902041b58377218",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575031835605.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": " ",
        "timestamp": "2019-11-30T06:51:18.936Z",
        "_id": "5de211665c3f2c26c00fe64f",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575096678917.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": "null",
        "timestamp": "2019-11-30T06:51:41.060Z",
        "_id": "5de2117d5c3f2c26c00fe650",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575096701051.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": "swqdwqd wwwwdwq",
        "timestamp": "2019-11-30T07:05:22.398Z",
        "_id": "5de214b2964be62d78358f87",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575097522372.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    },
    {
        "description": "swqdwqd wwwwdwq",
        "timestamp": "2019-11-30T07:36:48.894Z",
        "_id": "5de21c1006f2b81790276f6a",
        "name": "topics test xqxq",
        "thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575099408870.jpg",
        "category_id": "5de0fe0b4f76c22ebce2b70a",
        "__v": 0
    }
      ]
}

回答by Yuci

You can use a middleware to set the default Content-Type, and set Content-Type differently for particular APIs. Here is an example:

您可以使用中间件设置默认的 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>`);
})

回答by MalcolmOcean

For the header half of the question, I'm gonna give a shout out to res.typehere:

对于问题的标题部分,我要在res.type这里大喊:

res.type('json')

is equivalent to

相当于

res.setHeader('Content-Type', 'application/json')

Source: express docs:

来源:快递文档

Sets the Content-Type HTTP header to the MIME type as determined by mime.lookup() for the specified type. If type contains the “/” character, then it sets the Content-Type to type.

将 Content-Type HTTP 标头设置为 MIME 类型,由指定类型的 mime.lookup() 确定。如果 type 包含“/”字符,则将 Content-Type 设置为 type。

回答by Aung Zan Baw

Older version of Express use app.use(express.json())or bodyParser.json()read more about bodyParser middleware

旧版本的 Express 使用app.use(express.json())bodyParser.json()阅读有关 bodyParser 中间件的更多信息

On latest version of express we could simply use res.json()

在最新版本的 express 上,我们可以简单地使用 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}`))