1

There is excellent documentation and screencasts (Sailscasts) on how to make either a JSON API or an HTML (EJS) templated app using Sails.js, but is there a way to create a JSON API and an HTML webapp simultaneously. In rails this is done using either respond_to do |format| block or (in a more scalable fashion) with namespaced, versioned api routes and controllers.

http://www.emilsoman.com/blog/2013/05/18/building-a-tested/

is there something similar in sails.js?

2 Answers 2

2

ajbraus, I would recommend using the wantsJSON method instead. For example:

'/contentNegotiation': function(req, res) {

    // req.wantsJSON
    // https://github.com/balderdashy/sails/blob/master/lib/hooks/request/index.js#L282

    if (req.wantsJSON) {
        res.json(user);
    } else {
        res.redirect('/user');;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

So what determines if wantsJSON will be true? Is it the format of the request? So, if the request comes in as '/contentNegotiation.json' -> wantsJSON will be true?
1

One way to to do this is to build your own sailsy respond_to do |format| block

  if(req.isJson) {
    res.json(user); 
  }
  else {
    res.redirect('/user');  
  }

You could also add an req.isAjax response as well if you like. Used here https://www.youtube.com/watch?v=Di50_eHqI7I

But this is not namespaced routes and is therefore not as scalable and extensible as I'd like.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.