Question

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?

Was it helpful?

Solution

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'));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top