【问题标题】:Hapijs server start error - Invalid server optionsHapijs 服务器启动错误 - 无效的服务器选项
【发布时间】:2021-05-24 10:31:37
【问题描述】:

我正在使用这个简单的服务器程序

const Hapi = require('hapi');
const server = new Hapi.Server({
  host: 'localhost',
  port: 8080,
});

server.route({
  path: '/',
  method: 'GET',
  handler: (request, response) => {
    response(true);
  },
});

server.start(() => {
  console.log('Server running at:', server.info.uri);
});

这在服务器启动时给了我以下错误

throw new Error(msgs.join(' ') || 'Unknown error');
    ^

Error: Invalid server options {
  "port" [2]: 8080,
  "host" [1]: "localhost"
}

[1] "host" is not allowed
[2] "port" is not allowed
    at Object.exports.assert (/Users/aakashverma/Documents/exercises/makeithapi/node_modules/hoek/lib/index.js:736:11)
    at Object.exports.apply (/Users/aakashverma/Documents/exercises/makeithapi/node_modules/hapi/lib/schema.js:17:10)
    at new module.exports.internals.Server (/Users/aakashverma/Documents/exercises/makeithapi/node_modules/hapi/lib/server.js:32:22)
    at Object.<anonymous> (/Users/aakashverma/Documents/exercises/makeithapi/serveEm/serveEm.js:3:16)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Function.Module.runMain (module.js:701:10)

而我的package.json 的依赖项是这样设置的

"dependencies": {
    "axios": "^0.17.1",
    "hapi": "^16.6.2"
  }

我尝试到处搜索这个问题并找到了一个确切的here,但版本太旧无法比较。

我该如何解决这个问题?

【问题讨论】:

    标签: javascript node.js hapijs


    【解决方案1】:

    您要传递的选项需要传递给对server.connection() 的调用,而不是传递给Server 构造函数。

    来自hapi docs的片段:

    'use strict';
    
    const Hapi = require('hapi');
    
    const server = new Hapi.Server();
    server.connection({ port: 3000, host: 'localhost' });
    
    server.start((err) => {
    
        if (err) {
            throw err;
        }
        console.log(`Server running at: ${server.info.uri}`);
    });
    

    【讨论】:

      【解决方案2】:

      可能是错字问题? 因为在他们的示例代码here 中,他们用小写字母拼写了 server,并且您在示例仅使用该函数时创建了一个新实例。

      // Create a server with a host and port
      const server = Hapi.server({ 
          host: 'localhost', 
          port: 8000 
      });
      

      更新:

      显然,hapi的当前版本是17,问题是16。那么,16.6.2版本的服务器如何配置的详细信息可以在下面找到:

      https://hapijs.com/api/16.6.2

      【讨论】:

      • 我不这么认为。在hapi github 代码中,我发现了这两行exports.Server = Server;exports.server = Server;
      • 我明白了。您是否尝试过在不使用 new 关键字的情况下通过 Hapi.server(opts) 初始化服务器?
      • 不,不过不是我的问题。 ;-)
      • 我在本地尝试过,hapijs 提供的示例运行良好。您可以用整个文件的内容更新问题以进行比较吗?
      • 其实你上面给出的代码属于hapi v17.2,OP使用的是v16.6.2
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 2022-07-19
      • 2014-03-13
      • 2014-07-01
      • 2019-02-26
      • 2017-06-14
      • 2012-03-05
      相关资源
      最近更新 更多