Sailsjs:基于请求参数设置响应方法 [英] Sailsjs: Setting response method based on request parameter

查看:57
本文介绍了Sailsjs:基于请求参数设置响应方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我一直在使用 Sailsjs 进行 SPA 项目.问题是:

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

加载第一页时,我在控制器中使用 res.view res.render .但是,对于后续请求,我不想使用 res.view res.render ,而我想使用 res.json

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:

返回req.param('json')吗?res.json(myObj):res.view('layout',myObj);

这可行,但是我正在寻找一种更通用和抽象的方法,我的控制器本身会知道(基于 req.param('json'))是否使用 res.view res.json ,而无需我明确告知.

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.

有帮助吗?

推荐答案

这是 res.ok()的用途.

在下面的控制器操作中, res.ok 将使用 data 作为视图局部变量显示 myAction.ejs . data 作为JSON,具体取决于请求的发送方式(即通过AJAX,套接字或常规浏览器请求):

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);

    }

}

在内部, ok 响应使用 req.wantsJSON 来确定要做什么;它检查标头,查找 xhr 对象,通常会尽最大努力猜测您的意图. req.wantsJSON 可用于所有请求( req.isSocket 也是如此),因此您可以根据需要自己使用它们.

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.

这篇关于Sailsjs:基于请求参数设置响应方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆