間の実際の違いは何であるres.sendとres.jsonの両方としては、クライアントへの応答の同じ操作を実行しているようです。
間の実際の違いは何であるres.sendとres.jsonの両方としては、クライアントへの応答の同じ操作を実行しているようです。
回答:
オブジェクトまたは配列が渡される場合、メソッドは同一ですが、およびres.json()などの非オブジェクトも変換しますnullundefined、有効なJSONではないます。
メソッドはjson replacerおよびのjson spacesアプリケーション設定も使用するため、より多くのオプションでJSONをフォーマットできます。これらのオプションは次のように設定されています。
app.set('json spaces', 2);
app.set('json replacer', replacer);
そしてそのJSON.stringify()ように渡されました:
JSON.stringify(value, replacer, spacing);
// value: object to format
// replacer: rules for transforming properties encountered during stringifying
// spacing: the number of spaces for indentation
これは、res.json()sendメソッドにはないメソッド内のコードです。
var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);
メソッドres.send()は最終的にa になります。
this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');
return this.send(body);
res.json最終的にを呼び出しますがres.send、その前に次のようにします。
json spacesとjson replacerアプリの設定送信されたヘッダーを
確認します... res.sendはcontent-type:text / htmlを
使用しますres.jsonはcontent-type:application / jsonを使用します
res.json引数をJSONに強制します。 res.sendjson以外のオブジェクトまたは配列を受け取り、別のタイプを送信します。例えば:
これはJSON番号を返します。
res.json(100)
これにより、ステータスコードが返され、sendStatusを使用するように警告が発行されます。
res.send(100)
引数がJSONオブジェクトまたは配列(null、undefined、boolean、string)ではなく、JSONとして送信されるようにしたい場合は、を使用しますres.json。