ノードまたはExpressを使用してJSONに戻る正しい方法

6285 ワード

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 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」:しかし、これは2つの点で「問題」と論争することができます.
  • 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オブジェクトを送信するものであり、上述の第1の例と同様である.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 likeJSON.stringify(anObject, null, 3)この応答も文字列で、修飾された応答を送信する場合は、何らかの気まずい理由で使用できますJSON.stringify(anObject, null, 3)It's important that you set theContent-Typeheader toapplication/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 doJSON.stringify(...) + '\
    '
    to achieve that.なぜ改行で終了するのか分かりませんが、実行できますJSON.stringify(...) + '\
    '
    実現できます.
    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 3 x the response object has a json()method which sets all the headers correctly for you and returns the response in JSON format.Express.js 3 xから、すべてのヘッダを正しく設定し、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.パイプラインと多くのプロセッサの1つを使用して美化できます.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(`
            Tove
            Jani
            Reminder
            Don't forget me this weekend!
            `);
    })