nodejs的express框架的response常用返回方式

常用的返回方式有四种

  1. res.json()以json的形式返回数据

  2. res.render(view [, locals] [, callback])返回对应的view和数据,类似于spring的modelandview,此方法可以有回调函数,以处理可能出现的异常

  3. res.send(body) 返回自定义的数据,比如json或者404等状态

  4. res.redirect([status,] path) 这个方法其实不是返回,而是跳转到另外一个url上,类似于spring的redirect

首先还是先说res.json

官方文档
Sends a JSON response. This method is identical to res.send() with an object or array 
as the parameter. However, you can use it to convert other values to JSON, 
such as null, and undefined. (although these are technically not valid JSON).

渣翻译:可以发送一个json响应,这个方法同res.send()一样,同样都是以一个对象或者数组作为参数,你也可以把其他数据转换成json然后发送,例如,null, undefined ,尽管这些值可能不是正确的json

官方例子

res.json(null)     
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })    //返回错误码

如果你用ajax请求,可以使用此方法做返回

第二种是res.sender()

这就是spring的modelandview啊

前面是返回对应的视图名称(不加文件后缀),后面就是要返回的数据

官方文档
Renders a view and sends the rendered HTML string to the client. Optional parameters:

locals, an object whose properties define local variables for the view.

callback, a callback function. If provided, the method returns both 
the possible error and rendered string, but does not perform an automated response. 
When an error occurs, the method invokes next(err) internally.
渣翻译: 把渲染视图和html的字符串发送给客户端浏览器,可选参数有
本地变量:发送到此本地变量对应的视图的一个对象
回调函数:返回可能的错误和渲染字符串,但不执行自动响应。当发生错误时,该方法调用next(err)。

官方示例

// send the rendered view to the client
res.render('index');

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', function(err, html) {
  res.send(html);
});

// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function(err, html) {
  // ...
});

其中index是视图的名称,比如index.jade或者index.ejs等

不适用ajax,直接访问此url,获取返回值和模板,填充对应模板数据

第三个是res.send(),它可以返回自定义的属性

官方文档
Sends the HTTP response.
The body parameter can be a Buffer object, a String, an object, or an Array. 
渣翻译:发送一个http响应
参数可以是缓冲对象,字符串,对象,数则

官方示例

res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });

最后一个是res.redirect

举例说,当你添加了一个帖子,返回一个帖子的id,然后又想直接打开帖子的内容,这个就有了用途,它会跳转到对应的url上,就是重定向

官方文档
Redirects to the URL dervied from the specified path, with specified HTTP status code status. 
If you don’t specify status, the status code defaults to “302 “Found”.
渣翻译:重定向到从指定的路径的URL,与指定的HTTP状态代码状态。如果不指定状态,该状态代码默认为302。

官方示例

res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');
res.redirect('../login');

这方法就是让你去重定向的。



转载于:https://my.oschina.net/u/2519530/blog/535595

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值