gpt4 book ai didi

javascript - HAPI 17 : Routes not registered

转载 作者:行者123 更新时间:2023-11-30 20:47:20 24 4
gpt4 key购买 nike

您好,我正在从 Hapi 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。

最佳答案

您的路线文件的以下代码将起作用:

 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;
}
}

关于javascript - HAPI 17 : Routes not registered,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48567125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com