简介
Express的request可以用于获取前端传输过来的数据,而response则可以像前端返回数据,下面分别就接收前端数据和向前端返回数据的几个主要函数进行介绍。
Request
req.query
- 作用
- 用于获取复杂的get请求
- http请求中使用?作为请求参数和路由地址的分隔
- 用法
- 路由代码如下:
var express = require('express');
var app = express();
app.get('/test', function(){
});
- 请求与结果如下:
// GET /test?q=tobi+ferret
req.query.q
// => "tobi ferret"
// GET /test?order=desc&shoe[color]=blue&shoe[type]=converse
req.query.order
// => "desc"
req.query.shoe.color
// => "blue"
req.query.shoe.type
// => "converse"
req.params
- 作用
- 获取简单的get请求
- 用法
- 路由代码如下
var express = require('express');
var app = express();
app.get('/test/:username', function(){
});
- 请求与结果如下
// GET /user/tj
req.params.name
// => "tj"
req.body
- 作用
- 用于获取Post请求中的数据
- 用法
- 路由代码如下
var app = require('express')();
var bodyParser = require('body-parser');
app.post('/login', function (req, res) {
console.log(req.body);
res.json(req.body);
});
Response
res.end
res.end([data] [, encoding])
作用:用于快速的结束响应,可以不包含任何数据
res.json
- 语法:
res.json([body])
- 作用:
返回一个JSON格式的响应(通过JSON.stringify()进行的格式转换)
res.json(null);
res.json({ user: 'tobi' });
res.status(500).json({ error: 'message' });
res.redirect
- 语法
res.redirect([status,] path)
- 作用
- 指向特定的URL
res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');
res.redirect('../login')
res.render
- 语法
res.render(view [, locals] [, callback])
- 作用
- 渲染视图,并将其返回给客户端
- local参数定义了返回的视图中需要使用的局部变量
- 当添加回调函数时,如果获取文件成功,才会在回调函数中进一步执行
// 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) {
// ...
});
res.send
- 语法
res.send([body])
- 作用
- 发送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.end/res.json/res.send
- res.end 主要用于快速结束响应,可以不包含数据
- res.json 用于返回JSON格式的数据
- res.send 可以返回各类数据
- res.redirect/res.render
- res.redirect 主要用于指向特定的URL,当URL是本地的视图文件时,效果和res.render相同