Sailsjs: Setting response method based on request parameter

不问归期 提交于 2020-01-07 02:25:10

问题


So I have been working on a SPA project using Sailsjs. The problem is:

When the first page loads, I use res.view or res.render in my controller. But, for subsequent requests, I dont want to use res.view or res.render, rather I'd like to use res.json.

Right now, I use the method:

return req.param('json') ? res.json(myObj) : res.view('layout', myObj);

This works, but I was looking for a more generic and abstract method in which my controller itself would know (on the basis of req.param('json')) whether to use res.view or res.json without me having to tell it explicitly.

Any help ?


回答1:


This is what res.ok() is for.

In the controller action below, res.ok will either display the myAction.ejs using data as the view locals, or respond with data as JSON, depending on how the request came in (i.e. via AJAX, sockets or a regular browser request):

module.exports = {

    myAction: function(req, res) {

       var data = {someKey: "someVal"};

       return res.ok(data);

    }

}

Internally, the ok response uses req.wantsJSON to determine what to do; it checks headers, looks for an xhr object and generally does its best to guess your intent. req.wantsJSON is available for all requests (as is req.isSocket), so you can use them yourself as needed.




回答2:


So after a bit of tinkering, I resolved this using a service.

I wrote a service (in GlobalUtils.js):

render: function (req, res, obj) {
    if(req.param('json')) {
        return res.json(obj);
    }
    else {
        return res.view('layout', obj);
    }
}

And I use this service in my controllers, like so:

return GlobalUtils.render(req, res, myObj);

But still, looking for a better method.



来源:https://stackoverflow.com/questions/25682116/sailsjs-setting-response-method-based-on-request-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!