您好我从16岁迁移到Hapi 17.我将我的路由定义在另一个文件中,我试图将其注册为插件。但是当我调用API时,我得到了404。路由未在服务器中注册。
这是我的服务器代码。
'use strict'
const Hapi = require('hapi')
const server = new Hapi.Server({ port: 1234, host: 'localhost' });
const plugins = [{
plugin: require('vision'),
plugin: require('./methods/exampleMethod'),
plugin: require('./routes/devices')
}]
async function registerPlugin(){
await server.register(plugins)
}
registerPlugin().then( () => {server.start()})

这是我的路线文件devices.js:
exports.plugin = {
register: (server, options) =>
{
server.routes = [{
method: 'GET',
path: '/v1/devices',
handler: async function (request, h) {
const val = server.methods.testMethod("ankur")
const response = h.response('hello world ankur')
response.type('text/plain')
return response
}
}]
},
name: 'devices'
}

方法文件
exports.plugin = {
register: (server, options) => {
server.method(
{
name: 'testMethod',
method: function (id) {
return new Promise(function (resolve, reject) {
return resolve("Test method called")
})
}
})
},
name: "exampleMethod"

我正在关注Hapi 17的发行说明,并尝试将路由注册为自定义插件。但是,当我点击Get v1 / devices时,我得到了404.
答案 0 :(得分:1)
您的路线文件的以下代码将起作用:
exports.plugin = {
register: (server, options) => {
server.route(
{
method: "GET",
path: "/v1/devices",
handler: async function(request, h) {
//const val = server.methods.testMethod("ankur")
const response = h.response("hello world ankur");
response.type("text/plain");
return response;
}
}
);
},
name: "devices"
};

您应该使用路由对象调用server.route()函数。
如果您想通过路由插件注册多个功能,请使用以下内容:
exports.plugin = {
register: (server, options) => {
const routes = [
{
method: "GET",
path: "/v1/devices",
handler: async function(request, h) {
const response = h.response("hello world");
response.type("text/plain");
return response;
}
},
{
method: "GET",
path: "/v1/another",
handler: async function(request, h) {
const response = h.response("hello another world");
response.type("text/plain");
return response;
}
}
];
server.route(routes);
},
name: "devices"
};

编辑:
方法插件
exports.plugin = {
register: (server, options) => {
server.method("testMethod", async function(id) {
return "Test method called";
});
},
name: "exampleMethod"
};

调用方法:
{
method: "GET",
path: "/v1/example",
handler: async function(request, h) {
const response = await request.server.methods.testMethod();
return response;
}
}