【发布时间】:2017-12-12 02:07:39
【问题描述】:
没有发出我的 Express 'end' 事件。请提供一些关于如何修复它的提示。
快速设置:
//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. 我是否应该将 req.on('data') 和 req.on('end') 放在 app.use() 上,因为我想在各种 PUT 和 POST 上获取整个请求?
3. 如果我不使用req.on,即使我的body小于1MB,我也会得到partial body吗?
如果您需要更多信息,请告诉我。 谢谢。
================================================ =========
已解决:
请参阅下面的 Sandip 解决方案。
总之,
对于 http PUT,我们应该使用 bodyParser.json 或 req.on('end', function),但不能同时使用。对于 http POST,我们应该同时使用;
bodyParser.json 返回的结果是 req.body,它是一个 JSON 对象,而 req.on('end', function) 在我的代码中返回一个字符串;
谢谢大家!
【问题讨论】: