我正在类似于我正在观看的Nuxt教程的javascript项目中使用hapi-nuxt
。我使用以下命令生成了框架应用程序:
npx create-nuxt-app <project-name>
这在server / index.js中提供了以下代码:
const Hapi = require('hapi')
const consola = require('consola')
const HapiNuxt = require('hapi-nuxt')
const server = new Hapi.Server({
host: process.env.HOST || 'localhost',
port: process.env.PORT || 3000
})
server
.register({
plugin: HapiNuxt
})
.then(() => server.start())
.then(() =>
consola.ready({
message: `Server running at: ${server.info.uri}`,
badge: true
})
)
.catch(err => {
consola.error(err)
throw err
})
现在,我要添加server / routes / index.js中列出的路由。我相信代码类似于:
const routes = require('./routes');
...
routes.forEach(route => {
app.route(route);
}
假设代码正确,我应该放在哪里?
答案 0 :(得分:1)
这是一个例子
// server/index.js
const consola = require('consola')
const Hapi = require('@hapi/hapi')
const HapiNuxt = require('@nuxtjs/hapi')
const Routes = require('./api')
async function start() {
const server = new Hapi.Server({
host: process.env.HOST || '127.0.0.1',
port: process.env.PORT || 3000
})
await server.register({
plugin: HapiNuxt,
options: {}
});
await server.route(Routes);
await server.start()
consola.ready({
message: `Server running at: ${server.info.uri}`,
badge: true
})
}
process.on('unhandledRejection', (error) => consola.error(error))
start()
// server/api/index.js
const route1 = {
path: '/api',
method: 'GET',
handler (request, h) {
return {
works: true
}
}
}
module.exports = [
route1
]