简介
Express的request可以用于获取前端传输过来的数据,而response则可以像前端返回数据,下面分别就接收前端数据和向前端返回数据的几个主要函数进行介绍。
Request
req.query
- 作用
- 用于获取复杂的get请求
- http请求中使用?作为请求参数和路由地址的分隔
- 路由代码如下:
var express = require('express');
var app = express();
app.get('/test', function(){
});
- 请求与结果如下:
// GET /test?q=tobi+@R_78_5023@
req.query.q
// => "tobi @R_78_5023@"
// 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])
- 作用
// 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。