Her ikisi arasındaki gerçek fark nedir res.sendve res.jsonher ikisi de istemciye yanıt verme işlemini aynı şekilde yapıyor gibi görünüyor.
Her ikisi arasındaki gerçek fark nedir res.sendve res.jsonher ikisi de istemciye yanıt verme işlemini aynı şekilde yapıyor gibi görünüyor.
Yanıtlar:
Bir nesne veya dizi iletildiğinde yöntemler aynıdır, ancak geçerli JSON olmayan ve res.json()gibi nesneler olmayanları da dönüştürecektir .nullundefined
Yöntem ayrıca json replacerve json spacesuygulama ayarlarını kullanır , böylece JSON'u daha fazla seçenekle biçimlendirebilirsiniz. Bu seçenekler şu şekilde ayarlanır:
app.set('json spaces', 2);
app.set('json replacer', replacer);
Ve JSON.stringify()böyle bir şeye geçti :
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()Gönderme yönteminin sahip olmadığı yöntemdeki kod :
var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);
Yöntem res.send()sonunda bir sona erer :
this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');
return this.send(body);
res.jsonsonunda arar res.send, ama ondan önce:
json spacesve json replaceruygulama ayarlarına saygı duyarGönderilen başlıklara bakıldığında ...
res.send, content-type: text / html
res.json, content-type: application / json kullanır
res.jsonargümanı JSON'a zorlar. res.sendjson olmayan bir nesne veya dizi alır ve başka bir tür gönderir. Örneğin:
Bu bir JSON numarası döndürür.
res.json(100)
Bu bir durum kodu döndürecek ve sendStatus'u kullanmak için bir uyarı verecektir.
res.send(100)
Argümanınız bir JSON nesnesi veya dizisi (null, undefined, boolean, string) değilse ve JSON olarak gönderildiğinden emin olmak istiyorsanız, kullanın res.json.