Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out if controller should return JSON using wantsJSON

Tags:

sails.js

I saw that in sails there is a variable in the request object called wantsJSON and in the error pages that gets generated when creating a new project, it shows

if (req.wantsJSON) {
    //Do Something
} 

How does sails decide whether a user wants JSON or not?

like image 831
clifford.duke Avatar asked Dec 21 '25 23:12

clifford.duke


1 Answers

Sails decides that from the request. You can find it in the source code . I've copied and commented the interesting part for you:

// True, if the request has a xhr polling origin. (via socket)
req.wantsJSON = req.xhr;

// True, if the above was false (or null) and the origin not only accepts html.
// See HTTP header field 'Accept'
req.wantsJSON = req.wantsJSON || !req.explicitlyAcceptsHTML;

// True, if everything above was false (or null) and the origins content type 
// is json and the header field 'Accept' is set.
// See HTTP header field 'Content-type'
req.wantsJSON = req.wantsJSON || (req.is('json') && req.get('Accept'));
like image 132
Robin Avatar answered Dec 24 '25 04:12

Robin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!