Express HTTP請求中的請求訊息(req)和響應訊息(res)
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/tj
req.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.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended:true})); // for parsing application/x-www-form-urlencoded
app.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+ferret
req.query.q
// => "tobi ferret"
// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
req.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 format
if (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-urlencoded
app.use(express.urlencoded({ extended: false }))
app.get('/', function(req, res){
if (req.cookies.remember) {
res.send('Remembered :). Click to <a 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');