Whe n bạn nhập app.use(express.bodyParser())
, gần như mỗi yêu cầu sẽ trải qua các chức năng bodyParser
(cái nào sẽ được thực hiện tùy thuộc vào tiêu đề Content-Type
).
Theo mặc định, có 3 tiêu đề được hỗ trợ (AFAIR). Bạn có thể thấy các nguồn để chắc chắn. Bạn có thể (lại) xác định xử lý cho Content-Type
s với một cái gì đó như thế này:
var express = require('express');
var bodyParser = express.bodyParser;
// redefine handler for Content-Type: multipart/form-data
bodyParser.parse('multipart/form-data') = function(req, options, next) {
// parse request body your way; example of such action:
// https://github.com/senchalabs/connect/blob/master/lib/middleware/multipart.js
// for your needs it will probably be this:
next();
}
UPD.
Mọi thứ đã thay đổi trong tốc 3, vì vậy tôi chia sẻ đang được cập nhật từ dự án làm việc (nên app.use
ed trướcexpress.bodyParser()
):
var connectUtils = require('express/node_modules/connect/lib/utils');
/**
* Parses body and puts it to `request.rawBody`.
* @param {Array|String} contentTypes Value(s) of Content-Type header for which
parser will be applied.
* @return {Function} Express Middleware
*/
module.exports = function(contentTypes) {
contentTypes = Array.isArray(contentTypes) ? contentTypes
: [contentTypes];
return function (req, res, next) {
if (req._body)
return next();
req.body = req.body || {};
if (!connectUtils.hasBody(req))
return next();
if (-1 === contentTypes.indexOf(req.header('content-type')))
return next();
req.setEncoding('utf8'); // Reconsider this line!
req._body = true; // Mark as parsed for other body parsers.
req.rawBody = '';
req.on('data', function (chunk) {
req.rawBody += chunk;
});
req.on('end', next);
};
};
Và một số mã giả, liên quan đến câu hỏi ban đầu:
function disableParserForContentType(req, res, next) {
if (req.contentType in options.contentTypes) {
req._body = true;
next();
}
}
Aaaarg! Tôi đã dành hơn một ngày cố gắng tìm ra lý do tại sao tôi không thể tải lên các tập tin khi các ứng dụng mẫu (không có Express, nhưng cũng rõ ràng, với nhiều sự khác biệt khác quá) làm việc hoàn hảo. Hóa ra 'bodyParser' là thủ phạm. Cảm ơn bạn đã hỏi điều này. – meloncholy