首页 > 编程知识 正文

Express HTTP请求中的请求消息(req)和响应消息(res)

时间:2023-05-06 14:20:26 阅读:217604 作者:2415

本文摘抄自菜鸟教程 Express 4.x API中文文档

Request

req 对象代表了一个HTTP请求,其具有一些属性来保存请求中的一些数据,比如query string,parameters,body,HTTP headers等等。在本文档中,按照惯例,这个对象总是简称为 req ( http响应简称为res ),但是它们实际的名字由这个回调方法在那里使用时的参数决定。 如下例子:

app.get('/user/:id', function(req, res) { res.send("user" + req.params.id);})

其实你也可以这样写:

app.get('/user/:id', function(request, response) { response.send("user" + request.params.id);}) Properties(特性)

Express 4中,req.files 默认在req对象中不再是可用的。为了通过 req.files 对象来获得上传的文件,你可以使用一个 multipart-handling (多种处理的工具集)中间件,比如busboy,multer,formidable,multipraty,connect-multiparty或者pez。


req.params

一个对象,其包含了一系列的属性,这些属性和在路由中命名的参数名是一一对应的。例如,如果你有/user/:name路由,name属性可作为req.params.name。这个对象默认值为{}。

// GET /user/tjreq.params.name// => "tj"


req.body

在请求的 body 中保存的是提交的一对对键值数据。默认情况下,它是 undefined,微笑的小白菜使用比如 body-parser 和 multer 这类解析 body 数据的中间件时,它是填充的。 下面的例子,给你展示了怎么使用 body-parser 中间件来填充 req.body。该方法一般用来处理 POST 请求提交的参数.

var app = require('express');var bodyParser = require('body-parser');var multer = require('multer');// v1.0.5var upload = multer(); // for parsing multipart/form-dataapp.use(bodyParser.json()); // for parsing application/jsonapp.use(bodyParser.urlencoded({extended:true})); // for parsing application/x-www-form-urlencodedapp.post('/profile', upload.array(), function(req, res, next) { console.log(req.body); res.json(req.body);});


req.query

一个对象,为每一个路由中的query string参数都分配一个属性。如果没有query string,它就是一个空对象,{}。 该方法通常用来处理 GET 请求提交的参数 // GET /search?q=tobi+ferretreq.query.q// => "tobi ferret"// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=conversereq.query.order// => "desc"req.query.shoe.color// => "blue"req.query.shoe.type// => "converse"


req.cookies

当使用 cookie-parser 中间件的时候,这个属性是一个对象,其包含了请求发送过来的 cookies。如果请求没有带 cookies,那么其值为{}。

/** * Module dependencies. */var express = require('../../');var app = module.exports = express();var logger = require('morgan');var cookieParser = require('cookie-parser');// custom log formatif (process.env.NODE_ENV !== 'test') app.use(logger(':method :url'))// parses request cookies, populating// req.cookies and req.signedCookies// when the secret is passed, used// for signing the cookies.app.use(cookieParser('my secret here'));// parses x-www-form-urlencodedapp.use(express.urlencoded({ extended: false }))app.get('/', function(req, res){ if (req.cookies.remember) { res.send('Remembered :). Click to <a rel="external nofollow" href="/forget">forget</a>!.'); } else { res.send('<form method="post"><p>Check to <label>' + '<input type="checkbox" name="remember"/> remember me</label> ' + '<input type="submit" value="Submit"/>.</p></form>'); }});app.get('/forget', function(req, res){ res.clearCookie('remember'); res.redirect('back');});app.post('/', function(req, res){ var minute = 60000; if (req.body.remember) res.cookie('remember', 1, { maxAge: minute }); res.redirect('back');});/* istanbul ignore next */if (!module.parent) { app.listen(3000); console.log('Express started on port 3000');}

关于cookieParser的更多详细信息 , 可以查阅 cookie-parser


req.route

当前匹配的路由,其为一串字符。比如:

app.get('/user/:id?', function userIdHandler(req, res) { console.log(req.route); res.send('GET')}) Response

res 对象代表了当一个HTTP请求到来时,Express 程序返回的HTTP响应。在本文档中,按照惯例,这个对象总是简称为 res ( http请求简称为 req ),但是它们实际的名字由这个回调方法在那里使用时的参数决定。 例如:

app.get('/user/:id', function(req, res) { res.send('user' + req.params.id);});

这样写也是一样的:

app.get('/user/:id', function(request, response) { response.send('user' + request.params.id);}); Properties (特性)


res.send([body])

发送HTTP响应。body参数可以是一个Buffer对象,一个字符串,一个对象,或者一个数组。比如: 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' });

对于一般的非流请求,这个方法可以执行许多有用的的任务:比如,它自动给Content-LengthHTTP响应头赋值(除非先前定义),也支持自动的HEAD和HTTP缓存更新。
当参数是一个Buffer对象,这个方法设置Content-Type响应头为application/octet-stream,除非事先提供,如下所示:

res.set('Content-Type', 'text/html');res.send(new Buffer('<p>some html</p>'));

当参数是一个字符串,这个方法设置Content-Type响应头为text/html:

res.send('<p>some html</p>');

当参数是一个对象或者数组,Express使用JSON格式来表示:

res.send({user:'tobi'});res.send([1, 2, 3]);


res.end([data] [, encoding])

结束本响应的过程。这个方法实际上来自Node核心模块
用来快速结束请求,没有任何的数据。如果你需要发送数据,可以使用 res.send() 和 res.json() 这类的方法。


res.redirect([status,] path)

重定向来源于指定path的URL,以及指定的HTTP status codestatus。如果你没有指定status,status code默认为”302 Found”。

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

重定向也可以是完整的URL,来重定向到不同的站点。

res.redirect('http://google.com');</p><p>重定向也可以相对于主机的根路径。比如,如果程序的路径为<strong>http://example.com/admin/post/new</strong>,那么下面将重定向到<strong>http://example.com/admim</strong>:</p><pre>res.redirect('/admin');

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。