My Express“结束”事件未发出。请撕碎一些有关如何修复它的提示。
快速设置:
//Enable CORS
console.log("Enabled CORS and all pre-flight request");
app.use(cors())
app.options('*', cors()) // enable pre-flight request for ALL request
app.use(bodyParser.json({ type: 'application/*+json' })); //James 11/7/2017
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ limit: '10mb', extended: true }));
路由器设置:
//update
app.put('/:resourceType/id/:idPatient', function (req, res, next) {
console.log("update by Id [" + req.params.resourceType + "][" + req.params.idPatient + "][" + JSON.stringify(req.body) + "]");
gModel.fhirUpdateById(req, res, next, false); // isDeleted = false
});
每次都能看到上面的console.log
,
// Handler
module.exports.fhirUpdateById = function (req, res, next, isDeleted) {
var body = '';
//Test 1: Direct call without req.on, then can't parse the body
//updateById((req.params.resourceType, req.params.resourceId, res, next, req.body, isDeleted));
//Test 2:
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
console.log("fhirUpdateById Resource type: [" + req.params.resourceType + "] Body: [" + body + "]");
updateById((req.params.resourceType, req.params.resourceId, res, next, body, isDeleted));
});
}
上面的console.log
永远不会显示。 req.on('end', function () ...)
从未被触发;)
问题:
1. 如何修复req.on('end'...)触发?
2. 由于我想在各种 PUT 和 POST 上获取整个请求,我是否应该将 req.on('data') 和 req.on('end') 放在 app.use() 上?
3. 如果我不使用req.on,即使我的body小于1MB,我也会得到部分body吗?
如果您需要更多信息,请告诉我。 谢谢。
================================================== =========
已解决:
请参阅下面 Sandip 的解决方案。
总而言之,
对于 http PUT,我们应该使用 bodyParser.json 或 req.on('end', function),但不能同时使用两者。对于http POST,我们应该同时使用两者;
bodyParser.json 返回的结果是 req.body,它是一个 JSON 对象,而 req.on('end', function) 在我的代码中返回一个字符串;
谢谢大家!
最佳答案
发现问题了。如果您使用主体解析器中间件,则不会触发请求对象上的任何 data
或 end
事件。我从代码中删除了正文解析器,事件开始触发。实际上,主体解析器会为您完成您试图通过 data
事件监听器实现的工作。
因此,您要么完全删除正文解析器
//Enable CORS
console.log("Enabled CORS and all pre-flight request");
app.use(cors())
app.options('*', cors()) // enable pre-flight request for ALL request
//update
app.put('/:resourceType/id/:idPatient', function (req, res, next) {
console.log("update by Id [" + req.params.resourceType + "][" + req.params.idPatient + "][" + JSON.stringify(req.body) + "]");
gModel.fhirUpdateById(req, res, next, false); // isDeleted = false
});
或者,您应该使用 body 解析器并直接从 req.body
获取数据
要了解其工作原理,您可以查看此 article
关于node.js - Express req.on ('end' , ...) 未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47764319/