У меня есть API, который возвращает файл по трубопроводу в ответе читаемого потока в узле.Я также хочу вернуть JSON-содержимое tokenBody
в ответе, но не могу понять, куда вставить JSON при построении потокового ответа.Я получаю файл в ответ просто отлично.Я могу видеть правильные данные JSON при регистрации запроса.Он сидит в местном вар tokenBody
.Какие-либо предложения?Установка res.body = tokenBody
была моей мыслью, но выдает ошибку res.body is not a function
.
ОБНОВЛЕНИЕ Я могу вернуть JSON с res.json(tokenBody);
, но узел выдает ошибку cant set headers after they are sent
, и больше необслуживает файл в ответе, только JSON.кажется, что я могу сделать только одно или другое.Любой способ сделать оба?
app.get('/:token', function(req, res, next) {
// first need to check whether user's allowed to have access to this token
checkAllowedManageTokens(req.apiUserId, 'read')
.then(function(constraints) {
var query = queryPushAndCondition({token: req.params.token}, constraints);
return tokenModel.findOne(query);
})
.then(function(obj){
if (isDefined(obj)) {
var tokenBody = objToJSON(obj);
// Retrieve the file and send it back to the user
var gfs = Grid(tokenDB.getConnection().db, tokenDB.getDriver());
var readStream = gfs.createReadStream({filename:obj.filename});
console.log("Token Body Response " + JSON.stringify(tokenBody));
// Set response headers
res.status(200);
if (isDefined(obj.mimeType)) res.contentType(obj.mimeType);
// Pipe the response data
readStream.pipe(res);
} else {
clientError(res, "Not found");
}
})
.catch(function(err){
console.error('Token GET error: '+err.message);
serverError(res, 'err.message');
});
});