如何在 Nuxt.js 项目中使用 hapi-nuxt 添加后端路由?

How to add backend routes with hapi-nuxt in a Nuxt.js project?

我在 javascript 项目中使用 hapi-nuxt,类似于我正在观看的 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);
}

假设代码是正确的,我应该把它放在哪里?

这是一个例子

// 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
]