这是我的堆栈:
iOS 和 Android 应用
文档数据库
Javascript 支持的移动服务
由 Javascript 支持的 Azure 站点
我想要做的是从我们的应用程序中提取 DocumentDB 的知识,因为我们正在构建白标签解决方案,并且我们可能需要动态扩展 DocumentDB 实例。通过抽象类型的服务,我们基本上可以根据应用程序发送的某些数据对 docdb 实例进行分片。
现在,这将由我想为其创建移动服务的 2 个操作组成。一个用于获取 JSON 数据,另一个用于获取与文档关联的附件。这就是我的麻烦所在。我有一个仅用 NodeJS 编写的可部署的直通服务。我喜欢与移动服务相关的安全模型,因此我想将我的代码调整为该模型。问题在于将 DocDB 响应传送到移动服务响应。首先,尝试设置移动服务默认 header 但失败,因此我暂时覆盖该功能。现在,移动服务永远不会响应,直到发生超时。这是一个代码片段:
exports.get = function (req, res) {
...
// .then().fail() always pushed into the fail() block, but if I use the 2 function in .then() way it works.
client.readMediaAsync(mediaUrl).then(
// Success
function (media) {
// Set up caching and proxy the response
media.headers["cache-control"] = "max-age=2147483647, max-stale=2147483647";
media.headers["pragma"] = "cache";
for (var responseHeader in media.headers) {
if (media.headers.hasOwnProperty(responseHeader) && "content-location" != responseHeader) {
res.setHeader(responseHeader, media.headers[responseHeader]);
}
}
// Block further header modification
res.setHeader = function(field, val){};
media.result.pipe(res, {end: true});
//media.result.on("end", function () {
// console.log("attachment#end");
// res.status(200).send(); // have also tried .end() with no luck
//});
},
// Error
function (mediaError) {
console.error("documentClient.readMediaAsync fail->" + JSON.stringify(mediaError));
res.status(400).send(JSON.stringify(mediaError));
}
); ...
读取 media.result.pipe(...) 的行是挂起的地方。同样,此代码在移动服务之外运行。我一直在使用更改 -> 提交 -> 测试 -> 重复循环,但没有任何运气。有人知道如何正确地将流传输到移动服务中的响应中吗?
最佳答案
我成功重现了您的问题,请求一段时间后我得到了 HTML 代码,但是我还在 LOGS 选项卡中收到了错误消息,它看起来像:
An unhandled exception occurred. Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (http.js:679:11) at ServerResponse.res.setHeader (D:\home\site\wwwroot\node_modules\express\node_modules\connect\lib\patch.js:59:22) at ServerResponse.res.set.res.header (D:\home\site\wwwroot\node_modules\express\lib\response.js:518:10) at addDefaultHeaders (D:\home\site\wwwroot\runtime\request\requesthandler.js:582:9) at ServerResponse.<anonymous> (D:\home\site\wwwroot\runtime\request\requesthandler.js:291:13) at ServerResponse._.wrap [as end] (D:\home\site\wwwroot\node_modules\underscore\underscore.js:692:22) at onend (stream.js:66:10) at EventEmitter.emit (events.js:126:20) at afterRead (fs.js:1335:12) at Object.wrapper [as oncomplete] (fs.js:367:17)
根据此日志,我在通过管道输入响应之前设置了 header ,并且在我的测试中运行良好。
这是我的简单代码片段:
exports.get = function(request, response) {
var fs = require("fs");
response.setHeader = function(field, val){};
fs.createReadStream('files/123.txt').pipe(response,{end: true});
};
关于node.js - 移动服务+DocumentDB附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33503851/