node.js - hapi 中的服务器方法是否可以返回文件

标签 node.js hapi.js

我尝试将 reply.file ( http://hapijs.com/api#replyfilepath-options ) 用于 server.method ( http://hapijs.com/api#servermethodname-fn-options ),但它说我的 next 函数没有 file:

Debug: hapi, internal, implementation, error
    TypeError: Uncaught error: Object function (err, result) {

                methodNext(err, result, null, { msec: timer.elapsed(), error: err });
            } has no method 'file'
    at /Users/user/Work/Dev/export.js:37:12
    at ChildProcess.<anonymous> (/Users/user/Work/Dev/node_modules/webshot/lib/webshot.js:221:9)
    at ChildProcess.emit (events.js:98:17)
    at Process.ChildProcess._handle.onexit (child_process.js:810:12)

我有以下内容:

server.method('getExport', function(reqParams, queryParams, hostUri, next) {

  // ...
  next.file(filePath, {
    // Download as an attachment
    mode: 'attachment'
  });

});


Instance.server.route({
  method: 'GET',
  path: '/export',
  config: {
    handler: function(req, reply) {
      var uri = req.server.info.uri;

      server.methods.getExport(
        req.params,
        req.query,
        uri,
        reply
      );
    }
  }
});

可能吗?

我使用的是 hapi v6.9。

最佳答案

当您调用该方法时,您必须向其传递一个回调方法。 https://github.com/hapijs/hapi/blob/83201d29bcc8c8edc46d9ecf4f1d51b7f3a3a4ff/lib/methods.js#L64

这是您的代码:

var hapi = require('hapi'),
    server = new hapi.Server('0.0.0.0', 5000);

server.method('getExport', function(reqParams, queryParams, hostUri, reply, next) {

  // ...
  reply.file('/tmp/test.js', {
    // Download as an attachment
    mode: 'attachment'
  });

  next();

});

server.route({
  method: 'GET',
  path: '/export',
  config: {
    handler: function(req, reply) {
      var uri = req.server.info.uri;

      server.methods.getExport(
        req.params,
        req.query,
        uri,
        reply,
        function () {
            console.log('ran');
        }
      );
    }
  }
});

server.start()

我强烈建议不要为此使用服务器方法,这对于使用文件进行回复似乎有点过分了。如果可能的话,我还强烈建议升级到最新版本的 hapi。

关于node.js - hapi 中的服务器方法是否可以返回文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26261925/

相关文章:

regex - 错误 : pattern must be a RegExp

node.js - 在nodejs应用程序中了解我的客户端IP

javascript - 从 Node 上传时文件损坏

javascript - POST 请求后下载 CSV

javascript - res.end() 是否结束 async.waterfall?

node.js - 酱汁实验室点播 : multiCapabilities build information is not accepted

javascript - 如何将回调作为变量传递给 puppeteer 中的 page.evaluate?

javascript - Lodash 相当于 hoek.reach (hapijs)?

javascript - 根据另一键的输入,根据需要进行一个输入

javascript - 如何将 HapiJs 连接到 Swagger?